【发布时间】:2020-07-19 21:55:05
【问题描述】:
如果以下模式允许重复,我无法使用 python re 模块使否定后向断言工作:
import re
ok = re.compile( r'(?<!abc)def' )
print( ok.search( 'abcdef' ) )
# -> None (ok)
print( ok.search( 'abc def' ) )
# -> 'def' (ok)
nok = re.compile( r'(?<!abc)\s*def' )
print( nok.search( 'abcdef' ) )
# -> None (ok)
print( nok.search( 'abc def' ) )
# -> 'def'. Why???
我的真实案例应用是我想在文件中找到匹配项,前提是匹配项前面没有'function':
# Must match
mustMatch = 'x = myFunction( y )'
# Must not match
mustNotMatch = 'function x = myFunction( y )'
# Tried without success (always matches)
tried = re.compile( r'(?<!\bfunction\b)\s*\w+\s*=\s*myFunction' )
print( tried.search( mustMatch ) )
# -> match
print( tried.search( mustNotMatch ) )
# -> match as well. Why???
这是限制吗?
【问题讨论】:
-
nok = re.compile( '(?<!abc)\s*def' )应该是nok = re.compile( r'(?<!abc)\s*def' ) -
@ChrisCharley,虽然需要使用原始字符串,但模式本身的逻辑也是错误的。
-
@ChrisCharley 谢谢,我已经在问题中更正了它,但正如 JvdV 提到的那样,问题有更深的根源
标签: python negative-lookbehind re