详解python里使用正则表达式的全匹配功能

yipeiwu_com5年前Python基础

详解python里使用正则表达式的全匹配功能

python中很多匹配,比如搜索任意位置的search()函数,搜索边界的match()函数,现在还需要学习一个全匹配函数,就是搜索的字符与内容全部匹配,它就是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制作钉钉加密/解密工具

又是很久没有写技术博客了,盖因最近都在学习知识,也没有总结出什么值得分享的内容,所以一直停笔至今。最近的工作和钉钉的开发打上了交到,官方并没有提供任何Python的SDK,于是只能全部自...

python查询mysql中文乱码问题

问题: python2.7 查询或者插入中文数据在mysql中的时候出现中文乱码 --- 可能情况: 1.mysql数据库各项没有设置编码,默认为'latin' 2.使用MySQL.co...

python re.sub()替换正则的匹配内容方法

如下所示: import re c = re.compile(r'\d') s = 'you1are2welcome' # 用指定的内容,替换正则匹配的内容,也可以指...

Python实现查找二叉搜索树第k大的节点功能示例

Python实现查找二叉搜索树第k大的节点功能示例

本文实例讲述了Python实现查找二叉搜索树第k大的节点功能。分享给大家供大家参考,具体如下: 题目描述 给定一个二叉搜索树,找出其中第k大的节点 就是一个中序遍历的过程,不需要额外的...

在Python的Django框架中编写编译函数

当遇到一个模板标签(template tag)时,模板解析器就会把标签包含的内容,以及模板解析器自己作为参数调用一个python函数。 这个函数负责返回一个和当前模板标签内容相对应的节点...