Get named groups from a regular expression

MRAB python at
Tue Jul 1 18:53:03 CEST 2014

On 2014-07-01 16:12, Florian Lindner wrote:
> Hello,
> Is there a way I can extract the named groups from a regular expression?
> e.g. given "(?P<testgrp>\d)" I want to get something like ["testgrp"].
> OR
> Can I make the match object to return default values for named groups, even
> if no match was produced?
>>> import re
>>> r = re.compile(r"(?P<testgrp>\d)")
>>> r.groupindex
{'testgrp': 1}

i.e. there's a named group called 'testgrp' whose group number is 1.

More information about the Python-list mailing list