Python Regex - 如何获取匹配的位置和值 [英] Python Regex - How to Get Positions and Values of Matches
本文介绍了Python Regex - 如何获取匹配的位置和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 re
模块获取所有匹配项的开始和结束位置?例如,给定模式 r'[a-z]'
和字符串 'a1b2c3d4'
我想得到它找到每个字母的位置.理想情况下,我也想取回比赛的文本.
How can I get the start and end positions of all matches using the re
module? For example given the pattern r'[a-z]'
and the string 'a1b2c3d4'
I'd want to get the positions where it finds each letter. Ideally, I'd like to get the text of the match back too.
推荐答案
import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
print(m.start(), m.group())
这篇关于Python Regex - 如何获取匹配的位置和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文