【问题标题】:python regex: duplicate names in named groupspython regex:命名组中的重复名称
【发布时间】:2017-11-11 15:21:22
【问题描述】:

有没有办法在 python 的正则表达式命名组中使用相同的名称? 例如(?P<n>foo)|(?P<n>bar).

用例: 我正在尝试使用此正则表达式捕获 typeid
/(?=videos)((?P<type>videos)/(?P<id>\d+))|(?P<type>\w+)/?(?P<v>v)?/?(?P<id>\d+)?
从这个字符串:

  • /channel/v/123
  • /ch/v/41500082
  • /频道
  • /videos/41500082

现在我收到错误: redefinition of group name 'id' as group 6; was group 3

【问题讨论】:

  • 一个命名的捕获组是唯一的,除非您使用仅由较新的regex 模块支持的分支重置:(?|...) - 您是否有在线演示您正在尝试什么达到?此外,条件正则表达式或环视很可能就足够了。

标签: python regex regex-lookarounds regex-group


【解决方案1】:

答案是:Python re 不支持同名组

Python PyPi regex module 支持分支重置功能

分支重置

(?|...|...)

捕获组编号将在备选方案中重复使用,但名称不同的组将具有不同的组编号。

示例:

>>> regex.match(r"(?|(first)|(second))", "first").groups()
('first',)
>>> regex.match(r"(?|(first)|(second))", "second").groups()
('second',)

请注意,只有一组。

这是现场直播Python 2.7 demo

import regex
s = "foo bar"
rx = regex.compile(r"(?P<n>foo)|(?P<n>bar)")
print([x.group("n") for x in rx.finditer(s)])
// => ['foo', 'bar']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2020-05-10
    • 2022-07-01
    • 1970-01-01
    • 2021-06-26
    • 2016-12-15
    • 2021-06-09
    相关资源
    最近更新 更多