Python正则表达式前向/后向断言及否定模式详解
本文详解Python中正则表达式的前向与后向搜索断言语法。通过实例演示如何使用(?=pattern)实现一致性匹配,如成对出现的尖括号。同时深入讲解前向否定模式(?!pattern)的应用,以过滤特定邮箱地址为例,展示如何在不消耗字符的前提下进行条件判断与排除。
前言
在实际开发中,许多需要匹配的内容往往具有关联性,即要么同时出现,要么同时不出现。例如《》或< >这类成对的符号,绝不会只出现半个。为了在正则表达式中实现这种一致性约束——即要么两个尖括号同时存在,要么完全不存在——我们需要引入新的语法结构:(?=pattern)。该语法用于执行前向或后向搜索,若条件不满足则无法匹配。值得注意的是,这种匹配方式不会消耗输入字符串中的任何字符,它仅起到查看和断言的作用。
具体示例如下:
#python 3.6
#蔡军生
#http://blog.csdn.net/caimouse/article/details/51749579
#
import re
address = re.compile(
'''''
# A name is made up of letters, and may include "."
# for title abbreviations and middle initials.
((?P<name>
([\w.,]+\s+)*[\w.,]+
)
\s+
) # name is no longer optional
# LOOKAHEAD
# Email addresses are wrapped in angle brackets, but only
# if both are present or neither is.
(?= (<.*>$) # remainder wrapped in angle brackets
|
([^<].*[^>]$) # remainder *not* wrapped in angle brackets
)
<? # optional opening angle bracket
# The address itself: username@domain.tld
(?P<email>
[\w\d.+-]+ # username
@
([\w\d.]+\.)+ # domain name prefix
(com|org|edu) # limit the allowed top-level domains
)
>? # optional closing angle bracket
''',
re.VERBOSE)
candidates = [
u'First Last <first.last@example.com>',
u'No Brackets first.last@example.com',
u'Open Bracket <first.last@example.com',
u'Close Bracket first.last@example.com>',
]
for candidate in candidates:
print('Candidate:', candidate)
match = address.search(candidate)
if match:
print(' Name :', match.groupdict()['name'])
print(' Email:', match.groupdict()['email'])
else:
print(' No match')
运行结果如下:
Candidate: First Last <first.last@example.com> Name : First Last Email: first.last@example.com Candidate: No Brackets first.last@example.com Name : No Brackets Email: first.last@example.com Candidate: Open Bracket <first.last@example.com No match Candidate: Close Bracket first.last@example.com> No match
Python中正则表达式的前向否定模式
在前文学习的前向或后向搜索模式(?=pattern)中,等号“=”代表肯定相等。然而,前向搜索模式还包含不相等的判断逻辑。例如,在识别电子邮件地址如noreply@example.com时,这类地址通常无需回复,因此我们需要将其识别并排除。此时应使用前向否定模式,其语法为(?!pattern),其中的感叹号“!”表示非或排除。以字符串noreply@example.com为例,该模式会判断前缀是否匹配noreply@,若匹配则丢弃该结果,不再进行后续匹配。
具体示例如下:
#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
总结
以上就是本文的全部内容,希望这些内容能对各位的学习或工作有所帮助。如有任何疑问,欢迎留言交流,感谢大家对本站的支持。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













