代码之家  ›  专栏  ›  技术社区  ›  Bogaso

从列表中返回与模式匹配的元素

  •  1
  • Bogaso  · 技术社区  · 5 月前

    我有一个单词列表如下:

    STR = ['aa', 'dffg', 'aa2', 'AAA3']
    

    我想从上面的列表中获取与字符串匹配的元素列表:

    to_match = 'aa'
    

    我尝试了下面的代码:

    import re
    [re.findall(to_match, iWord) for iWord in STR]
    # [['aa'], [], ['aa'], []]
    

    然而,我想得到一个清单,比如 ['aa', 'aa2', 'AAA3'] .

    2 回复  |  直到 5 月前
        1
  •  4
  •   Barmar    5 月前

    试着先把单词放低:

    result = [s for s in STR if to_match in s.lower()]
    
        2
  •  0
  •   Timur Shtatland    5 月前

    使用 re.search ,带着国旗 re.IGNORECASE 进行不区分大小写的匹配,如下所示。

    请注意,为了清楚起见并符合Python命名约定,我还重命名了您的变量。

    import re
    
    strings = ['aa', 'dffg', 'aa2', 'AAA3']
    pattern = 'aa'
    matching_strings = [s for s in strings if re.search(pattern, s, re.IGNORECASE)]
    print(matching_strings)
    # ['aa', 'aa2', 'AAA3']
    

    请注意 re.findall 返回一个列表,这就是为什么您发布的代码会返回一系列列表。其中一些内部列表是空的,对应于模式所在的原始列表中的元素 发现。