我尝试了接受的答案正则表达式匹配单词前面没有紧接着另一个单词,但可能之前有该单词,但这不起作用。
>>> re.search('(?<!nonland) onto the battlefield', "When you cast this spell, reveal the top X cards of your library. You may put a nonland permanent card with mana value X or less from among them onto the battlefield. Then shuffle the rest into your library.")
<re.Match object; span=(144, 165), match=' onto the battlefield'>
>>> re.search('^.*?(?<!nonlaxnd)(?<!\W)\W*\bonto the battlefield\b.*', "When you cast this spell, reveal the top X cards of your library. You may put a nonland permanent card with mana value X or less from among them onto the battlefield. Then shuffle the rest into your library.")
>>> # basically only match good when no bad:
>>> re.search('(?<!bad) good', "other bad other good.")
<re.Match object; span=(15, 20), match=' good'>
我想
in
如此简单解释了为什么 Python 的内置 re
模块不执行可变长度后向查找。
>>> s = "other bad other good."; 'good' in s and not re.search('bad.*good', s)
False
>>> s = "other baod other good."; 'good' in s and not re.search('bad.*good', s)
True