re的finditer()


在前面学习了findall()函数,它可以一次性找到多个匹配的字符串,但是不能提供所在的位置,并且是一起返回的,如果有数万个一起返回来,就不太好处理了,因此要使用finditer()函数来实现每次只返回一个,并且返回所在的位置,如下例子:

[python] view plain copy
  1. #python 3. 6  
  2. #蔡军生   
  3. #http://blog.csdn.net/caimouse/article/details/51749579  
  4. #  
  5. import re  
  6.   
  7. text = 'http://blogcsdn.net/caimouse abbaaabbbbaaaaa'  
  8.   
  9. pattern = 'ab'  
  10.   
  11. for match in re.finditer(pattern, text):  
  12.     s = match.start()  
  13.     e = match.end()  
  14.     print('Found {!r} at {:d}:{:d}'.format(  
  15.         text[s:e], s, e))  



结果输出如下:

Found 'ab' at 29:31
Found 'ab' at 34:36