python正则表达式:命名组中的重复名称 [英] python regex: duplicate names in named groups

查看:47
本文介绍了python正则表达式:命名组中的重复名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 python 中的正则表达式命名组中使用相同的名称?例如(?Pfoo)|(?Pbar).

Is there a way to use same name in regex named group in python? e.g.(?P<n>foo)|(?P<n>bar).

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

Use case: I am trying to capture type and id with this regex:
/(?=videos)((?P<type>videos)/(?P<id>\d+))|(?P<type>\w+)/?(?P<v>v)?/?(?P<id>\d+)?
from this strings:

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

现在我收到错误:重新定义组名'id'为组6;是第 3 组

推荐答案

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

The answer is: Python re does not support identically named groups.

Python PyPi regex 模块 支持 分支重置功能:

Python PyPi regex module supports a branch reset feature:

分支重置

(?|...|...)

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

Capture group numbers will be reused across the alternatives, but groups with different names will have different group numbers.

示例:

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

注意只有一组.

这里是 Python 2.7 演示:

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']

这篇关于python正则表达式:命名组中的重复名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆