本文主要是介绍python 正则表达式 finditer,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
re.finditer
和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。
样例:
# -*- coding: UTF-8 -*-import reit = re.finditer(r"\d+","12a32bc43jf3")
for match in it: print (match.group()) # group() 代表 match.groups[0]
输出:
12
32
43
3
# -*- coding:UTF8 -*-import repattern = re.compile(r'\d+') # 查找数字
result1 = pattern.findall('runoob 123 google 456')
输出:
['123', '456']
finditer 其他用法
import re
# re.DOTALL 正则表达式里的句号(.)是匹配任何除换行符之外的字符。re.DOTALL 要求它连换行符也匹配
reg = re.compile("(//\s+@python\(([^\n]*?)\))", re.DOTALL)
a = "// @python(hello)// @python(hello)"
it = list(reg.finditer(a))
for x in it:print(x.groups())print(x[1])print(x)print(x.end()) # 打印match终结的位置
输出:
('// @python(hello)', 'hello')
// @python(hello)
<re.Match object; span=(0, 17), match='// @python(hello)'>
17
('// @python(hello)', 'hello')
// @python(hello)
<re.Match object; span=(17, 34), match='// @python(hello)'>
34
这篇关于python 正则表达式 finditer的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!