Nested Regex Conditionals
Paul Dale
pd at traxon.com
Tue Aug 23 11:58:13 EDT 2005
Hi All,
I know that several of you will probably want to reply "you should write
a parser", and I may. For that matter any tips on theory in that
direction would be appreciated.
However, if you would indulge me in my regex question I would also be
most grateful.
I'm writing an edi parser and to be in compliance with the specification
I need to have conditionals that are dependent on conditionals. In some
regular expression implementations this is possible. The code ...
#!/usr/bin/env python
import re
pattern = re.compile(r"""
(?P<first>(first))
(?(first)
(?P<second>(second))
)
(?(second)
(?P<third>(third))
)
""", re.VERBOSE)
string = 'firstsecondthird'
match = re.match(pattern,string)
print match.group('first','second','third')
Prints ('first', 'second', None)
and I haven't found any way to have a second conditional, nor any
reference to it in any documentation I've found.
Am I missing something, and it is possible? Or is it not possible in python?
It seems like it might be a bug, as it knows there is a group (None,
instead of an IndexError), but it doesn't match ...
Thanks for any help :)
Paul
More information about the Python-list
mailing list