1

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! that helped a lot! I made up the regex for example only so yeah its super fugly
@Leonard Lie No worries. Glad to help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.