python3 re返回形式总结
作者:小妮浅浅 时间:2023-12-23 16:40:07
我们在进行程序操作的时候,因为各种原因,需要通过不同的形式返回到之前的对象。不知道小伙伴们会几种返回的函数方法呢?今天要介绍的是findall和finditer这一对小伙伴,它们在输出的形式上有所不同。在这里小编先卖一个关子,想要知道答案的小伙伴,我们接着往下看。
findall(pattern, string, flags=0)
在字符串string中匹配所有符合正则表达式pattern的对象,并把这些对象通过列表list的形式返回。
import re
pattern = re.compile(r'\W+')
result1 = pattern.findall('hello world!')
result2 = pattern.findall('hello world!', 0, 7)
print(result1) #[' ', '!']
print(result2) #[' ']
finditer(pattern, string, flags=0)
在字符串string中匹配所有符合正则表达式pattern的对象,并把这些对象通过迭代器的形式返回。
import re
pattern = re.compile(r'\W+')
result = pattern.finditer('hello world!')
for r in result:
print(r)
# <re.Match object; span=(5, 6), match=' '>
# <re.Match object; span=(11, 12), match='!'>
Python3 Re常用方法
常用的功能函数包括:compile、search、match、split、findall(finditer)、sub(subn)
1.compile
re.compile(pattern[, flags])
作用:把正则表达式语法转化成正则表达式对象
flags定义包括:
re.I:忽略大小写
re.L:表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境
re.M:多行模式
re.S:' . '并且包括换行符在内的任意字符(注意:' . '不包括换行符)
re.U: 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依赖于 Unicode 字符属性数据库
2.search
re.search(pattern, string[, flags])
作用:在字符串中查找匹配正则表达式模式的位置,返回 MatchObject 的实例,如果没有找到匹配的位置,则返回 None。
3.match
re.match(pattern, string[, flags])
match(string[, pos[, endpos]])
作用:match() 函数只在字符串的开始位置尝试匹配正则表达式,也就是只报告从位置 0 开始的匹配情况,
而 search() 函数是扫描整个字符串来查找匹配。如果想要搜索整个字符串来寻找匹配,应当用 search()。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
导航与搜索合并的可能性
![](https://img.aspxhome.com/file/UploadPic/20099/27/nav_search-33s.png)
MySQL时间盲注的五种延时方法实现
![](https://img.aspxhome.com/file/2023/1/121581_0s.png)
Python实现发送带有pdf附件的电子邮件
![](https://img.aspxhome.com/file/2023/4/76924_0s.png)
好用的VSCode头部注释插件Fileheader Pro
python实点云分割k-means(sklearn)详解
![](https://img.aspxhome.com/file/2023/0/96920_0s.jpg)
JavaScript Memoization
小程序开发之uniapp引入iconfont图标以及使用方式
![](https://img.aspxhome.com/file/2023/1/135741_0s.png)
python 如何停止一个死循环的线程
![](https://img.aspxhome.com/file/2023/6/112106_0s.png)
python eventlet绿化和patch原理
Numpy中的mask的使用
![](https://img.aspxhome.com/file/2023/2/87572_0s.jpg)
Python异步操作MySQL示例【使用aiomysql】
tensorflow 实现从checkpoint中获取graph信息
SQL Server下几个危险的扩展存储过程
python中plt.imshow与cv2.imshow显示颜色问题
![](https://img.aspxhome.com/file/2023/9/71459_0s.jpg)
Python实现OCR识别之pytesseract案例详解
![](https://img.aspxhome.com/file/2023/2/94702_0s.png)
jQuery选择器 学习总结
linux采用binary方式安装mysql
python原类、类的创建过程与方法详解
Python数据可视化教程之Matplotlib实现各种图表实例
![](https://img.aspxhome.com/file/2023/8/101158_0s.png)
Pyhon Flask框架:第一个Flask程序
![](https://img.aspxhome.com/file/2023/3/81833_0s.png)