我有一个正则表达式匹配要求。我想匹配一个完整的短语而不是单个子标记。这是一个例子

In [21]: re.findall(r"""don't|agree|don't agree""", "I don't agree to this", re.IGNORECASE)
Out[21]: ["don't", 'agree']


我希望它分别匹配"don't agree"而不是don't and 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)

10-08 12:54