re的finditer()

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

[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))  



结果输出以下:app

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

相关文章
相关标签/搜索