我正在遍历列表“titles”中的字符串,我想打印“keywords\u to\u match”中单词匹配的字符串:
# import re
titles = ['walk to new zealand' , 'fly to mars' , 'drive to murica']
keywords_to_match = re.compile(r'(new zealand)?(mars)?(murica)')
for title in titles:
# if any of words inside keywords_to_match are matched print title
if keywords_to_match.search(title.lower()):
print(title)
# only prints "drive to murica"
这只打印“drive to murica”,但我希望它打印“titles”中的所有3个字符串
用“|”代替“?”来表达或表达关系
https://docs.python.org/3/library/re.html
将正则表达式更改为:
我不确定你的案子需要正则表达式。您可以简单地执行以下操作:
这同样有效
keywords_to_match = re.compile(r'(new zealand|mars|murica)')
相关问题 更多 >
编程相关推荐