Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named non-capturing group in python?

Tags:

python

regex

Is it possible to have named non-capturing group in python? For example I want to match string in this pattern (including the quotes):

"a=b" 'bird=angel'

I can do the following:

s = '"bird=angel"'
myre = re.compile(r'(?P<quote>[\'"])(\w+)=(\w+)(?P=quote)')
m = myre.search(s)
m.groups()
# ('"', 'bird', 'angel')

The result captures the quote group, which is not desirable here.

like image 204
qed Avatar asked May 09 '13 21:05

qed


1 Answers

No, named groups are always capturing groups. From the documentation of the re module:

Extensions usually do not create a new group; (?P<name>...) is the only exception to this rule.

And regarding the named group extension:

Similar to regular parentheses, but the substring matched by the group is accessible within the rest of the regular expression via the symbolic group name name

Where regular parentheses means (...), in contrast with (?:...).

like image 79
Bakuriu Avatar answered Sep 28 '22 05:09

Bakuriu