Search code examples
pythonregexstringlist

Return elements from a list that match a pattern


I have a list of words as below:

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

I want to get a list of elements from the above list that match a string:

to_match = 'aa'

I tried the code below:

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

However, I wanted to get a list like ['aa', 'aa2', 'AAA3'].


Solution

  • Use re.search, with the flag re.IGNORECASE to do case-insensitive matching, as shown below.

    Note that I also renamed your variables for clarity and to conform with Python naming conventions.

    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']
    

    Note that re.findall returns a list, which is why the code you posted returns a list of lists. Some of these inner lists are empty, corresponding to the elements of your original list where the pattern was not found.