我有正则表达式匹配要求。我想匹配一个完整的短语而不是单个的子语句。这是一个例子
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
。
任何帮助。
答案 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