Get named groups from a regular expression

Philip Shaw jnufcvyvuc at tznvy.pbz
Fri Jul 4 01:30:24 CEST 2014


On 2014-07-01, Florian Lindner <mailinglists at xgm.de> wrote:
>
> 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"].

The match object has an attribute called "groupdict", so you can get
the found named groups using match.groupdict.keys. I can't remember
what happens to unnamed groups (I prefer to name every group I want),
but ISTR that there is a list of capture groups in which the indexes
are the capture groups number (i.e. what you'd use to backreference
them).

> Can I make the match object to return default values for named
> groups, even if no match was produced?

A lazy solution I've used was to write a default dict, then update it
with the groupdict. I doubt that's all that efficient, but the
defaults were constant strings and the program was network-bound
anyway.



More information about the Python-list mailing list