re的finditer()
在前面学习了findall()函数,它可以一次性找到多个匹配的字符串,但是不能提供所在的位置,并且是一起返回的,如果有数万个一起返回来,就不太好处理了,因此要使用finditer()函数来实现每次只返回一个,并且返回所在的位置,如下例子:
[python] view plain copy- #python 3. 6
- #蔡军生
- #http://blog.csdn.net/caimouse/article/details/51749579
- #
- 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))
结果输出如下:
Found 'ab' at 29:31
Found 'ab' at 34:36