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

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

win7+Python3.5下scrapy的安装方法

win7+Python3.5下scrapy的安装方法

如何在win7+Python3.5的环境下安装成功scrapy? 通过pip3 install Scrapy直接安装,一般会报错:error: Unable to find vcvars...

Numpy截取指定范围内的数据方法

如下所示: lst = [[1,2,3,4,5,6], [7,8,9,10,11,12], [71,81,91,101,111,121]] arr = np.asarray(lst)...

python实现Dijkstra静态寻路算法

python实现Dijkstra静态寻路算法

算法介绍 迪科斯彻算法使用了广度优先搜索解决赋权有向图或者无向图的单源最短路径问题,算法最终得到一个最短路径树。该算法常用于路由算法或者作为其他图算法的一个子模块。 当然目前也有人将它用...

Python编程实现控制cmd命令行显示颜色的方法示例

Python编程实现控制cmd命令行显示颜色的方法示例

本文实例讲述了Python编程实现控制cmd命令行显示颜色的方法。分享给大家供大家参考,具体如下: 基于win7 + python3.4 运行效果: import ctypes i...

Python中List.index()方法的使用教程

 index()方法返回obj出现在列表中最低位索引。 语法 以下是index()方法的语法: list.index(obj) 参数   &...