如果以下模式允许重复,我无法使用 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???
这是一个限制吗?