我有正则表达式匹配要求。我想匹配一个完整的短语而不是单个子标记。这是一个例子
In [21]: re.findall(r"""don't|agree|don't agree""", "I don't agree to this", re.IGNORECASE)
Out[21]: ["don't", 'agree']
我希望它匹配“不同意”
,而不是分别匹配不同意和同意
。
任何帮助。
最佳答案
将最长的字符串放在前面:
re.findall(r"don't agree|don't|agree", "I don't agree to this", re.IGNORECASE)
或使用可选组:
re.findall(r"don't(?: agree)?|agree", "I don't agree to this", re.IGNORECASE)
关于Python 匹配贪婪短语搜索。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22559890/