Jack Smother
Jack Smother

Reputation: 207

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 validate "WHATEVER AND SO ON" for this example.

I tried finding about this around but couldn't find any solution.

Upvotes: 1

Views: 284

Answers (2)

whereisalext
whereisalext

Reputation: 740

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.

Upvotes: 0

U2EF1
U2EF1

Reputation: 13259

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')

Upvotes: 1

Related Questions