Nested Regex Conditionals
Paul McGuire
ptmcg at austin.rr.com
Tue Aug 23 17:39:39 EDT 2005
This works (note relocated right paren at (?(second) ):
#!/usr/bin/env python
import re
original_pattern = re.compile(r"""
(?P<first>(first))
(?(first)
(?P<second>(second))
)
(?(second)
(?P<third>(third))
)
""", re.VERBOSE)
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 out:
('first', 'second', 'third')
The pyparsing alternative looks like:
first = Literal("first").setResultsName("first")
second = Literal("second").setResultsName("second")
third = Literal("third").setResultsName("third")
# define line
line = first + second + third
print line.parseString("firstsecondthird")
Prints out:
['first', 'second', 'third']
-- Paul
More information about the Python-list
mailing list