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

标签 python regex string

>>> 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信息],不做任何额外的字符串操作?也许就像循环并在这些返回的索引处查找正则表达式的每个片段,即 614

正则表达式中有没有直接的方法可以知道基于 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/

相关文章:

string - Scheme - 带过滤器的列表函数

c++ - 如果 cout 丢失,循环进入无限循环

python - 如何获取自在 praw 上发布帖子以来的时间

php - 我如何检查给定的 url 是否在某个域内? PHP

java - 支持字母表的 24 小时制的正确正则表达式是什么 (java)

javascript - 正则表达式获取具有不同协议(protocol)的域

java - 从 For 循环 Java 返回字符串值

python - 将 "Q12019"对象转换为 datetime64

python - 向左折叠值,Python/Pandas

python - 如何在 Python 中有效地模拟图像压缩伪影?