Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式-如何获取匹配的位置和值_Python_Regex - Fatal编程技术网

Python正则表达式-如何获取匹配的位置和值

Python正则表达式-如何获取匹配的位置和值,python,regex,Python,Regex,如何使用re模块获取所有匹配的开始和结束位置?例如,给定模式r'[a-z]'和字符串'a1b2c3d4',我想得到它找到每个字母的位置。理想情况下,我也想把比赛的文本拿回来。摘自 import re p = re.compile("[a-z]") for m in p.finditer('a1b2c3d4'): print(m.start(), m.group()) span()在一个元组中返回开始索引和结束索引。自从 match方法仅检查是否在字符串开头重新匹配, start()将

如何使用
re
模块获取所有匹配的开始和结束位置?例如,给定模式
r'[a-z]'
和字符串
'a1b2c3d4'
,我想得到它找到每个字母的位置。理想情况下,我也想把比赛的文本拿回来。

摘自

import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
    print(m.start(), m.group())

span()在一个元组中返回开始索引和结束索引。自从 match方法仅检查是否在字符串开头重新匹配, start()将始终为零。但是,RegexObject的搜索方法 实例扫描字符串,因此匹配可能不会从零开始 那样的话

对于Python3.x

from re import finditer
for match in finditer("pattern", "string"):
    print(match.span(), match.group())

对于字符串中的每个命中,您将获得分离的元组(分别包含匹配的第一个和最后一个索引)和匹配本身。

注意,span&group是为正则表达式中的多个捕获组编制索引的

regex_with_3_groups=r"([a-z])([0-9]+)([A-Z])"
for match in re.finditer(regex_with_3_groups, string):
    for idx in range(0, 4):
        print(match.span(idx), match.group(idx))

看看这是否有助于使用它,比如
re.search(r'abbit',“has abbit of carrot”).span(0)
--
-(4,9)
span()
返回的“结束索引”类似于Python切片符号中的“停止”,因为它上升到但不包括该索引;请参阅。这不提供匹配regex=r'([a-z])(0-9)“m.start将用于group(),而不是group(1)@StevenWernerCS
start()
可能接受组号,因此如果您想要第n组的索引,请使用
start(n)
@hi angle yep,请参阅我去年的答案,谢谢,这已经被证明是非常有用的,而且似乎相当隐蔽。此外,如果有人需要这样做:当使用命名捕获组时,可以使用.re.groupindex找到组的索引,然后使用您概述的方法从中找到相应的跨度
4
从何而来?\u regex+1中已知组的@RadioControlled number\u,如范围所示[开始,结束]不包括end@StevenWernerCS所以它不能推广到群的数目未知的情况。。。
for match in re.finditer(r'[a-z]', 'a1b2c3d4'):
   print match.span()
from re import finditer
for match in finditer("pattern", "string"):
    print(match.span(), match.group())
regex_with_3_groups=r"([a-z])([0-9]+)([A-Z])"
for match in re.finditer(regex_with_3_groups, string):
    for idx in range(0, 4):
        print(match.span(idx), match.group(idx))