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

yipeiwu_com4年前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操作kafka实践的示例代码

python操作kafka实践的示例代码

1、先看最简单的场景,生产者生产消息,消费者接收消息,下面是生产者的简单代码。 #!/usr/bin/env python # -*- coding: utf-8 -*- impor...

Python利用神经网络解决非线性回归问题实例详解

Python利用神经网络解决非线性回归问题实例详解

本文实例讲述了Python利用神经网络解决非线性回归问题。分享给大家供大家参考,具体如下: 问题描述 现在我们通常使用神经网络进行分类,但是有时我们也会进行回归分析。 如本文的问题: 我...

python 读写文件,按行修改文件的方法

如下所示: >>> f = open(r'E:\python\somefile.txt','w') 打开文件,写模式 >>> f.write...

在IPython中进行Python程序执行时间的测量方法

在写MATLAB的脚本的时候我时长会用tic、toc进行一下程序运行时间的测量。在Python中偶尔也会测试下,但是基本上都是靠使用time模块。接触了IPython之后突然间发现,原来...

python读取csv文件示例(python操作csv)

复制代码 代码如下:import csvfor line in open("test.csv"):name,age,birthday = line.split(",")name = na...