Introspect the regex part that generated group in Python's 're'

Viewed 68

Is there a way of figuring out the actual string (or... sub-regular-expression... or... "chunk" of the regular expression) that generated a named group in a compiled Pattern?

For instance, something along the lines of:

>>> import re
>>> r = re.compile("foo(?P<bar>\d+)")

# The following is what I don't know how to do:
>>> sub_r = r.somethingsomething('bar')
>>> print(sub_r)

'\\d+'

I know I can get the names of the groups using r.groupindex and that r.pattern would give me the original string the full regex came from, yet I don't know how to combine both ideas (and it feels there must be a way):

>>> r.groupindex
mappingproxy({'bar': 1})

>>> r.pattern
'foo(?P<bar>\\d+)'
0 Answers
Related