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函數

相關文章
相關標籤/搜索