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

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

本文详细介绍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 相关产品和应用

全部下载

专题列表