【python】re模块的 findall 和 finditer 函数用法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【python】re模块的 findall 和 finditer 函数用法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2101字,纯文字阅读大概需要4分钟。
内容图文
![【python】re模块的 findall 和 finditer 函数用法](/upload/InfoBanner/zyjiaocheng/598/286c30b3504240e489a095b9dd777713.jpg)
python正则模块re中findall和finditer两者相似,但却有很大区别。
区别
- findall返回list
- finditer返回一个MatchObject类型的iterator
详细举例介绍
1、findall
在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表。
注意: match 和 search 是匹配一次, findall 匹配所有。
语法格式为:
findall(string[, pos[, endpos]])
参数:
参数 | 描述 |
---|---|
string | 待匹配的字符串。 |
pos | 可选参数,指定字符串的起始位置,默认为 0。 |
endpos | 可选参数,指定字符串的结束位置,默认为字符串的长度。 |
举例1:
import re
# 查找数字
pattern = re.compile(r'\d+')
# 查找方式1
result1 = pattern.findall('abc 123 bcd 456')
# 查找方式2(在字符串0到8位中查找数字)
result2 = pattern.findall('abc 123 bcd 456', 0, 8)
# 查找方式3,不使用compile
result3 = re.findall(r'\d+','abc 123 bcd 456')
print(result1)
print(result2)
print(result3)
输出
['123', '456']
['123']
['123', '456']
举例2:参数解析程序,实现将命令行各个参数解析出来。
import re
para = 'xcopy /s "c:\\program files" d:\\'
lists = re.findall(r'([^ "]+)|(".+?")', para)
print(lists)
for i in(lists):
for j in i:
if j !="":
print(j.strip('"'))
输出:
[('xcopy', ''), ('/s', ''), ('', '"c:\\program files"'), ('d:\\', '')]
xcopy
/s
c:\program files
d:
2、finditer
和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。
re.finditer(pattern, string, flags=0)
参数:
参数 | 描述 |
---|---|
pattern | 匹配的正则表达式 |
string | 要匹配的字符串。 |
flags | 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符 - 可选标志 |
举例1:
# -*- coding: UTF-8 -*-
import re
it = re.finditer(r"\d+","12a32bc43jf3")
for match in it:
print (match.group() )
输出:
12
32
43
3
举例2:参数解析程序,实现将命令行各个参数解析出来。
para = 'xcopy /s "c:\\program files" d:\\'
#匹配[^ "]不在[]中的字符 或者 匹配带引号的字符串
obj = re.finditer(r'([^ "]+)|(".+?")', para)
print(obj)
for i in obj:
print("groups:",i.groups())
print(i.group().strip('"'))
输出:
<callable_iterator object at 0x0000000002F2FA20>
groups: ('xcopy', None)
group: xcopy
groups: ('/s', None)
group: /s
groups: (None, '"c:\\program files"')
group: c:\program files
groups: ('d:\\', None)
group: d:
内容总结
以上是互联网集市为您收集整理的【python】re模块的 findall 和 finditer 函数用法全部内容,希望文章能够帮你解决【python】re模块的 findall 和 finditer 函数用法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。