在前面学习了findall()函数,它能够一次性找到多个匹配的字符串,可是不能提供所在的位置,而且是一块儿返回的,若是有数万个一块儿返回来,就不太好处理了,所以要使用finditer()函数来实现每次只返回一个,而且返回所在的位置,以下例子:python
- import re
-
- text = 'http://blogcsdn.net/caimouse abbaaabbbbaaaaa'
-
- pattern = 'ab'
-
- for match in re.finditer(pattern, text):
- s = match.start()
- e = match.end()
- print('Found {!r} at {:d}:{:d}'.format(
- text[s:e], s, e))
结果输出以下:app
Found 'ab' at 29:31
Found 'ab' at 34:36函数