Jack Smother Jack Smother - 1 year ago 90
Python Question

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.

Answer Source
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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download