Skip to main content
 首页 » 编程设计

python之确定 OR 正则表达式的哪个片段与字符串匹配

2024年10月24日21dflying

>>> import re 
>>> s = "These are the words in a sentence" 
>>> regex = re.compile('are|words') 
>>> [m.start(0) for m in re.finditer(regex,s)] 
[6, 14] 

是否有可能得到是在索引[6]上匹配,words在索引[14上匹配的信息],不做任何额外的字符串操作?也许就像在这些返回的索引处循环并找到正则表达式的每个片段,即 6 和 14。

在正则表达式中是否有直接的方法来知道匹配了基于 OR 的正则表达式的哪个片段?

请您参考如下方法:

这可以使用 re.MatchObject.group 来完成

来自文档

Returns one or more subgroups of the match. If there is a single argument, the result is a single string

(强调我的)

代码可以写成

>>> import re 
>>> s = "These are the words in a sentence" 
>>> regex = re.compile('are|words') 
>>> [(m.start(0),m.group()) for m in re.finditer(regex,s)] 
[(6, 'are'), (14, 'words')]