Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #88667
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: Get the numbering of named regex groups |
| Date | 2015-04-08 16:28 +0200 |
| Organization | None |
| References | <CAFPwPpSn0PGQHNTuNjOKB7fq30njPRyT-mzzRNd+URg4y7-gfg@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.140.1428503338.12925.python-list@python.org> (permalink) |
Mattias Ugelvik wrote:
> Example: re.match('(?P<first>a?)(?P<second>b?)', '')
>
> How can I find out that the group 'first' correlates to the positional
> regex group 1? I need to know this to resolve crucial ambiguities in a
> string manipulation tool I'm making. Looking at spans, as the example
> above illustrates, won't do the job.
>
> I can't see a way to do this through the documented interface (at
> least not in the `re` module?).
Compile and match in two separate steps:
>>> import re
>>> r = re.compile('(?P<first>a?)(?P<second>b?)')
Find the groups' positions:
>>> r.groupindex
{'second': 2, 'first': 1}
Find the matching substrings:
>>> r.match("a").groupdict()
{'second': '', 'first': 'a'}
https://docs.python.org/2.7/library/re.html#re.RegexObject.groupindex
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Get the numbering of named regex groups Peter Otten <__peter__@web.de> - 2015-04-08 16:28 +0200
csiph-web