Python匹配贪婪短语搜索。

时间:2014-03-21 13:17:03

标签: python regex

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

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

任何帮助。

2 个答案:

答案 0 :(得分:2)

将最长的字符串放在:

之前
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)

答案 1 :(得分:0)

在正则表达式中使用环视:

re.findall(r"""don't(?!\sagree)|(?<!don't\s)agree|don't agree""", "I don't agree to this", re.IGNORECASE)
                     ^^^^^^^^^   ^^^^^^^^^^

使用否定前瞻(?!\sagree)检查agree之后没有don't

并使用否定的lookbehind (?<!don't\s)检查don't

之前没有agree