Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #88669 > unrolled thread
| Started by | Mattias Ugelvik <uglemat@gmail.com> |
|---|---|
| First post | 2015-04-08 16:37 +0200 |
| Last post | 2015-04-08 16:37 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Get the numbering of named regex groups Mattias Ugelvik <uglemat@gmail.com> - 2015-04-08 16:37 +0200
| From | Mattias Ugelvik <uglemat@gmail.com> |
|---|---|
| Date | 2015-04-08 16:37 +0200 |
| Subject | Re: Get the numbering of named regex groups |
| Message-ID | <mailman.142.1428503828.12925.python-list@python.org> |
Thank god it's that easy! Err, I mean, thank you! I should have read
the docs more carefully :)
On 08/04/2015, Peter Otten <__peter__@web.de> wrote:
> 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
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
Back to top | Article view | comp.lang.python
csiph-web