我正在尝试使用执行以下操作的正则表达式:
匹配任何文字,不带“Chrome”字样,后跟“Safari”字样
我把一个不起作用的python脚本放在一起.
#!/usr/bin/env python
import sys
import re
# any text but 'Chrome' followed by Safari
negative_re = re.compile( '(?<!Chrome).*?Safari' )
matcher = negative_re.search( sys.argv[1] )
if matcher:
print "match"
else:
print "no match"
我尝试了以下示例
test_negative.py "Chrome Mobile/12345 Safari"
> match
test_negative.py "Like MAC OS Safari"
> match
我希望第一个返回“不匹配”,第二个返回“匹配”.如果有人可以帮助正则表达式,那将是伟大的,谢谢.
最佳答案 如果Safari跟随Chrome,然后否定条件,你难道不能只写正则表达式吗?
#!/usr/bin/env python
import sys
import re
# any text but 'Chrome' followed by Safari
negative_re = re.compile(r'Chrome.*Safari')
matcher = negative_re.search(sys.argv[1])
if matcher is None:
print "match"
else:
print "no match"
这对我来说似乎更容易.
结果:
mgilson@iris:~/sandbox$python test.py "Like MAC OS Safari"
match
mgilson@iris:~/sandbox$python test.py "Chrome Mobile/12345 Safari"
no match