您在那里遇到了一些问题。
首先,匹配项区分大小写,除非您使用
IGNORECASE/
I标志忽略大小写。因此,
'AND'不匹配
'and'。
另外,除非使用
VERBOSE/
X标志,否则这些空格是模式的一部分。因此,您正在检查
'AND',而不是
'AND'。如果需要,您可能希望在每一侧都留空格,而不仅是在那边(否则,
'bandleader'将要匹配…),而且实际上,您可能会想要
b,而不是空格(否则以开头的句子
'And another thing'将不匹配) 。
最后,如果你认为你需要
.*前,你的模式后
$,并
^围绕它,还有你想使用一个很好的机会
search,
findall或者
finditer,而不是
match。
所以:
>>> s = "These are oranges and apples and pears, but not pinapples or ..">>> r = re.compile(r'bANDb | bORb | bNOTb', flags=re.I | re.X)>>> r.findall(s)['and', 'and', 'not', 'or']
Debuggex演示



