re.finditer
和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并把它们作为一个迭代器返回。

样例:

# -*- coding: UTF-8 -*-
 
import re
 
it = re.finditer(r"\d+","12a32bc43jf3") 
for match in it: 
    print (match.group())  # group() 代表 match.groups[0]

输出:

12 
32 
43 
3
# -*- coding:UTF8 -*-
 
import re
 
pattern = 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
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐