详解Python中正则表达式的全匹配功能

Miles
Miles
发布时间:2026-10-13| 3人浏览过
原创

本文详细介绍Python中正则表达式的fullmatch()函数,该函数用于实现字符串与模式的全匹配。通过对比search()和match()函数,展示fullmatch()的具体用法及示例,帮助读者理解全匹配的概念与应用场景。

详解Python中正则表达式的全匹配功能

在Python中,正则表达式提供了多种匹配方式,例如search()函数用于搜索任意位置的匹配,match()函数用于匹配字符串边界。此外,还有一个重要的全匹配函数fullmatch(),它要求整个字符串必须与正则表达式完全匹配。

以下是fullmatch()函数的使用示例:

#python 3.6
#蔡军生 
#http://blog.csdn.net/caimouse/article/details/51749579
#
import re


text = 'This is some text -- with punctuation.'
pattern = 'is'


print('Text    :', text)
print('Pattern  :', pattern)


m = re.search(pattern, text)
print('Search   :', m)
s = re.fullmatch(pattern, text)
print('Full match :', s)




text = 'is'
print('Text    :', text)
s = re.fullmatch(pattern, text)
print('Full match :', s)


text = 'iss'
print('Text    :', text)
s = re.fullmatch(pattern, text)
print('Full match :', s)

运行上述代码后,输出结果如下:

Text    : This is some text -- with punctuation.
Pattern  : is
Search   : <_sre.SRE_Match object; span=(2, 4), match='is'>
Full match : None
Text    : is
Full match : <_sre.SRE_Match object; span=(0, 2), match='is'>
Text    : iss
Full match : None

如果您有任何疑问,欢迎留言或在本站社区交流讨论。感谢您的阅读,希望本文能对您有所帮助,也感谢大家对本站的支持!

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

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 算法库。