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')
我遇到的问题是正则表达式根本找不到名称并不断命中 else:
我已经尝试过re.search
, re.findall
, re.find
, re.match
, re.fullmatch
等等。他们都返回None
。它找到任何东西的唯一方法是如果我使用 re.finditer
但这不允许我使用 .group()
.
re.compile
的输出是 re.compile('\\b(Jim|Bob|Fred|Cam)\\b', re.IGNORECASE)
我在 https://regex101.com/ 上测试过它( ) 看起来它可以工作,但在 python 中却不起作用。
我错过了什么吗?
最佳答案
已编译正则表达式的第二个参数是字符串中开始搜索的位置,而不是与正则表达式一起使用的标志(第三个也是可选参数,是搜索的结束位置)。请参阅 Regular expression objects 的文档了解详情。
如果要指定不区分大小写的搜索,请将 re.IGNORECASE
传递给 re.compile
。对于此正则表达式,不需要 re.X
。
关于Python正则表达式不捕获单个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60961248/