>>> 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]
处匹配的are
信息,以及索引[14]处匹配的
,不做任何额外的字符串操作?也许就像循环并在这些返回的索引处查找正则表达式的每个片段,即 words
信息]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')]
关于python - 确定 OR 正则表达式的哪个片段与字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36766890/