在前面学习前向搜索或后向搜索模式(?=pattern),这个模式里看到有等于号=,它是表示一定相等,其实前向搜索模式里,还有不相等的判断。比如你需要识别EMAIL地址:noreply@example.com,这个EMAIL地址大多数是不需要回复的,所以我们要把这个EMAIL地址识别出来,并且丢掉它。怎么办呢?这时你就需要使用前向搜索否定模式,它的语法是这样:(?!pattern),这里的感叹号就是表示非,不需要的意思。比如遇到这样的字符串:noreply@example.com,它会判断noreply@是否相同,如果相同,就丢掉这个模式识别,不再匹配。例子如下:
结果输出如下:
Candidate: first.last@example.com
Match: first.last@example.com
Candidate: noreply@example.com
深入浅出Numpy
五子棋游戏开发
http://edu.csdn.net/course/detail/5487
#python 3.6
#蔡军生
#http://blog.csdn.net/caimouse/article/details/51749579
#
import re
address = re.compile(
'''
^
# An address: username@domain.tld
# Ignore noreply addresses
(?!noreply@.*$)
[\w\d.+-]+ # username
@
([\w\d.]+\.)+ # domain name prefix
(com|org|edu) # limit the allowed top-level domains
$
''',
re.VERBOSE)
candidates = [
u'first.last@example.com',
u'noreply@example.com',
]
for candidate in candidates:
print('Candidate:', candidate)
match = address.search(candidate)
if match:
print(' Match:', candidate[match.start():match.end()])
else:
print(' No match')
结果输出如下:
Candidate: first.last@example.com
Match: first.last@example.com
Candidate: noreply@example.com
No match