在前面學習了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函數