使用 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]