【问题标题】:Non capturing groups within named groups命名组中的非捕获组
【发布时间】: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


【解决方案1】:

我无法在命名组中使用非捕获组,但至少这将red 正确提取为group('color')

m = re.search(r"(?P<color>((red|green|blue)(?= is the color)|(?<=the color is )(red|green|blue)))", t)

【讨论】:

  • 谢谢 Serge,这个标题有点用词不当,但这个解决方案有效。
猜你喜欢
  • 2014-06-26
  • 1970-01-01
  • 1970-01-01
  • 2014-09-11
  • 2023-04-03
  • 1970-01-01
  • 2016-06-20
  • 1970-01-01
相关资源
最近更新 更多