使用 re.finditer 迭代匹配

你可以使用 re.finditer 迭代字符串中的所有匹配项。这给了你(与 re.findall 相比的额外信息,比如有关字符串中匹配位置的信息(索引):

import re
text = 'You can try to find an ant in this string'
pattern = 'an?\w' # find 'an' either with or without a following word character

for match in re.finditer(pattern, text):
    # Start index of match (integer)
    sStart = match.start()

    # Final index of match (integer)
    sEnd = match.end()

    # Complete match (string)
    sGroup = match.group()

    # Print match
    print('Match "{}" found at: [{},{}]'.format(sGroup, sStart,sEnd))

结果:

Match "an" found at: [5,7]
Match "an" found at: [20,22]
Match "ant" found at: [23,26]