1

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.

2
  • Does making each pattern a string and concatenating them not work? Commented Mar 2, 2014 at 0:37
  • Yeah but that might be limited functionality to what a string can hold.. Commented Mar 2, 2014 at 0:43

2 Answers 2

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')
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I know about * to give random example to the question and what the ability of the nested regex is. Will accept when available. Thank you!
#U2EF1 What would be the syntax to do more than one regex? Or is that not possible? r2 = re.compile(r'WHATEVER AND (%s)*' % r1.pattern, % r3.pattern)
I feel a moral obligation to point out that this example uses old-style string formatting, and the wave of the future in python is to use new-style string formatting, as in r2 = re.compile(r'WHATEVER AND ({})*'.format(r1.pattern)) There are many reasons why this is superior to the old-style syntax. To read them look here.
0

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.

Comments

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.