Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!newsfeed.xs4all.nl!newsfeed4.news.xs4all.nl!xs4all!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.001 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'example:': 0.03; '(at': 0.04; "'',": 0.07; 'string': 0.09; "'')": 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'steps:': 0.09; 'positional': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:plane.gmane.org': 0.16; 'received:t-ipconnect.de': 0.16; 'url:html#re': 0.16; 'url:re': 0.16; 'wrote:': 0.18; '>>>': 0.22; 'example': 0.22; 'import': 0.22; 'separate': 0.22; 'header :User-Agent:1': 0.23; 'documented': 0.24; 'least': 0.26; 'header:X -Complaints-To:1': 0.27; 'matching': 0.30; "i'm": 0.30; 'interface': 0.32; 'url:python': 0.33; 'subject:the': 0.34; "can't": 0.35; 'tool': 0.35; 'url:org': 0.36; 'two': 0.37; 'url:library': 0.38; 'to:addr:python-list': 0.38; 'to:addr:python.org': 0.39; 'received:org': 0.40; 'how': 0.40; 'subject:Get': 0.68; "'first'": 0.84; 'positions:': 0.84; 'subject:groups': 0.84; 'crucial': 0.91 X-Injected-Via-Gmane: http://gmane.org/ To: python-list@python.org From: Peter Otten <__peter__@web.de> Subject: Re: Get the numbering of named regex groups Date: Wed, 08 Apr 2015 16:28:49 +0200 Organization: None References: Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Gmane-NNTP-Posting-Host: p57bd88ed.dip0.t-ipconnect.de User-Agent: KNode/4.13.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.20 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 31 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1428503338 news.xs4all.nl 2845 [2001:888:2000:d::a6]:48112 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:88667 Mattias Ugelvik wrote: > Example: re.match('(?Pa?)(?Pb?)', '') > > 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('(?Pa?)(?Pb?)') 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