Skip to content Skip to sidebar Skip to footer

Nested Regular Expression In Python For

Is there a way to do nested regular expression in Python? For example I have r1 = re.compile(r'SO ON') can I have something like r2 = re.compile(r'WHATEVER AND (r1)*') to valida

Solution 1:

r1 = re.compile(r'SO ON')
r2 = re.compile(r'WHATEVER AND (%s)*' % r1.pattern)

This isn't actually using any special feature of regex, it's using string formatting. Multiple strings can be passed in as:

r'WHATEVER AND (%s) (%s)' % (r1.pattern, 'hello')

Solution 2:

I feel a moral obligation to point out that this is strictly supportive of regexen with no flags. As soon as you start using flags like re.MULTILINE this approach does not work. Perl was great with regex inside regex. I wish I could find a good Python solution.

Post a Comment for "Nested Regular Expression In Python For"