Python regex: duplicate names in named groups

Is it possible to use the same name in a group named regex in python? for example (?P<n>foo)|(?P<n>bar).

Use case: I am trying to capture typeand iduse this regular expression
/(?=videos)((?P<type>videos)/(?P<id>\d+))|(?P<type>\w+)/?(?P<v>v)?/?(?P<id>\d+)?
of these lines:

  • / channel / rev / 123
  • / h / r / 41500082
  • /channel
  • / video / 41500082

At the moment, I am getting the error: redefinition of group name 'id' as group 6; was group 3

+6
source share
1 answer

Answer: Python redoes not support identically named groups .

Python The PyPi module regexsupports the reset branch :

Branch reset

(?|...|...)

, .

:

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

All Articles