Python正则表达式前向/后向断言及否定模式详解

巷口听风
巷口听风
发布时间:2026-10-13| 2人浏览过
原创

本文详解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

总结

以上就是本文的全部内容,希望这些内容能对各位的学习或工作有所帮助。如有任何疑问,欢迎留言交流,感谢大家对本站的支持。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。