Python Regular Expression to Find All Matches in List

If you want to make use of Regular Expressions (RegEx) to find all matches within a Python list, you can make use of the re.findall() method.

Let's take a look at an example:

import re

def re_find_all_matches(pattern, city_list):
    matches = []
    for city in city_list:
        result = re.findall(pattern, city)
        matches.extend(result)
    return matches

city_list = ["New York", "Chicago", "Ohio", "Austin", "Texas","New York","Austin"]
pattern = r"Austin"

matches = re_find_all_matches(pattern, city_list)
print(matches)

Output:

['Austin', 'Austin']
Regex find all matches in List Python Example

Reference:

re.findall: https://docs.python.org/3/library/re.html?highlight=regular#re.findall

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!