user1054158
user1054158

Reputation:

Pattern associated to a named group

The following code gives all the named groups used in a pattern.

import re

pattern = r"(?P<DEF_FUNC>def (?P<NAME_FUNC>\w+)\s*\((.*?)\):)|(?P<OTHERS>\w+)"
regex   = re.compile(pattern)

for name in sorted(
    regex.groupindex,
    key = regex.groupindex.get
):
    print(name)

Here is the corresponding output.

DEF_FUNC
NAME_FUNC
OTHERS

I would like to also have the corresponding patterns so as to obtain the following output.

DEF_FUNC  --> def (?P<NAME_FUNC>\w+)\s*\((.*?)\)
NAME_FUNC --> \w+
OTHERS    --> \w+

Is there a tricky way to do that without doing it "at hand" via regex searches in the pattern text ?

Upvotes: 5

Views: 100

Answers (1)

perreal
perreal

Reputation: 97958

You can check sre_parse:

import re, sre_parse
pattern = r"(?P<DEF_FUNC>def (?P<NAME_FUNC>\w+)\s*\((.*?)\):)|(?P<OTHERS>\w+)"
v = sre_parse.parse(pattern)
print v.pattern.groupdict   # sub-pattern id of each group
#print v.dump()
print v.data  # find the subgroups and match the ids

Upvotes: 1

Related Questions