Jack Smother
Jack Smother

Reputation: 207

Nested grouping Regular Expression in Python

If I have several different regular expressions and I want to do nested regular expression like this

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

Now r3 works. But what if I want to do something like this

r4 = re.compile(r'(r1)(r2)(r1)(r2)(r2)' % (r1.pattern, 'r2.'pattern'))
##NOT VALID CODE, JUST FOR EXPLANATION

I reminded of using group capturing but they only match the exact same thing from where first group where it makes the match, not the pattern. Thanks

Upvotes: 1

Views: 440

Answers (1)

Justin O Barber
Justin O Barber

Reputation: 11591

I'm a little confused by your use of quotation marks, but you seem to be asking about string formatting. You can try to format your regex string like this:

>>> r'({r1})({r2})({r1})({r2})({r2})'.format(r1=r1.pattern, r2=r2.pattern)
'(SO ON)(WHATEVER AND (SO ON)*)(SO ON)(WHATEVER AND (SO ON)*)(WHATEVER AND (SO ON)*)'

So in your scenario, you could try a regex like this:

r4 = re.compile(r'({r1})({r2})({r1})({r2})({r2})'.format(r1=r1.pattern, r2=r2.pattern))

But you should attempt to find more concise ways to form this regex if at all possible.

Upvotes: 3

Related Questions