【发布时间】:2019-04-18 12:22:41
【问题描述】:
我想匹配一个带有前缀或后缀的字符串集合,例如
the color is red
red is the color
我想匹配组color: red
所以我的第一次尝试是显而易见的
(?<color>(?:the color is )(red|green|blue)|(red|green|blue)(?: is the color))
我期待这与一组 color: red 匹配,但它匹配 color: the color is red, 2: red
我也尝试过(?>) 原子运算符
我尝试将前缀/后缀组移到命名组之外:
(?:the color is )(?<color>red|green|blue)(?: is the color)
但这只会匹配带有前缀和后缀的字符串,例如the color is red is the color。也许我可以使用前瞻或后视运算符?
我无法将(?J) 修饰符用作我正在使用的正则表达式引擎(python re 模块不支持此功能。
【问题讨论】:
-
如果您使用 PCRE,您可以通过branch reset group 尝试。非捕获组看起来像是错误使用,因为它只是确保 get 中的内容没有被捕获(没有组输出/没有组索引)
-
你在
(?<=the color is )(?:red|green|blue)|(?:red|green|blue)(?= is the color)之后吗?见this regex demo。你真的需要命名的捕获组吗? -
@bobblebubble 不,OP 使用 Python。但是 PyPi 正则表达式支持很多特性,甚至是同名的捕获组。
-
@WiktorStribiżew 这是一个提炼的例子。实际上还有许多其他组,我宁愿命名组而不是依赖索引。
-
然后使用 PyPi 正则表达式模块。见rextester.com/NRXPIV89625
标签: python regex regex-group