Python Regex not capturing single strings

Viewed 71
bigger_list_of_names = ['Jim', 'Bob', 'Fred', 'Cam', 'Reagan','Alejandro','Dee','Rana','Denisha','Nicolasa','Annett','Catrina','Louvenia','Emmanuel','Dina','Jasmine','Shirl','Jene','Leona','Lise','Dodie','Kanesha','Carmela','Yuette',]
name_list = ['Jim', 'Bob', 'Fred', 'Cam']
search_people = re.compile(r'\b({})\b'.format(r'|'.join(name_list)), re.IGNORECASE)
print(search_people)

for names in bigger_list_of_names:
    found_them = search_people.search(names, re.IGNORECASE | re.X)
    print(names)
    if found_them:
        print('I found this person: {}'.format(found_them.group()))
    else:
        print('Did not find them')

The issue I am having is the regex does not find the names at all and keeps hitting the else: I have tried re.search, re.findall, re.find, re.match, re.fullmatch, etc. They all return None. The only way for it to find anything is if I use re.finditer but that would not allow me to use .group().

The output of the re.compile is re.compile('\\b(Jim|Bob|Fred|Cam)\\b', re.IGNORECASE)

I tested it on https://regex101.com/ (https://i.stack.imgur.com/lL3mh.png) and it looks like its working but not in the python.

Here is my console output: https://i.stack.imgur.com/kxdcc.png

Am I missing anything?

3 Answers

The second argument to a compiled regular expression is the position in the string to start searching, not flags to use with the regex (the third, also optional argument, is the ending position to search). See the docs for Regular expression objects for details.
If you want to specify a case-insensitive search, pass re.IGNORECASE to re.compile. For this regex, re.X isn't needed.

I'm a little late but I had the same issue before. It looks like you are using pycharm, if you check the auto complete thing (if you don't have it turned off) it would say:

pattern.search(self, string, pos, endpos)

Instead of adding flags in the .search() part, you will need to add the flags in the re.compile part. Since re.compile() actually accepts the flags.

What it looks like in pycharm auto complete:

re.compile(pattern, flags)

So it would look a bit like this:

search_people = re.compile(r'\b({})\b'.format(r'|'.join(name_list)), re.IGNORECASE | re.X)

for names in bigger_list_of_names:
    found_them = search_people.search(names)
    print(names)
    if found_them:
        print('I found this person: {}'.format(found_them.group()))
    else:
        print('Did not find them')

What you are trying to do, does not require a regex search. You can achieve the same as follows.

search_result = []
targets = set(names_list)
for name in set(bigger_list_of_names):
    if name in targets:
        search_result.append(name)
        print(f'Found name: {name}')
    else:
        print(f'Did not find name: {name}')
print(search_result)

Shorter version using list-comprehension

search_result = [name for name in set(bigger_list_of_names) if name in targets]
Related