2

In perl I can do this:

$number = qr/ zero | one | two | three | four | five | six | seven | eight | nine /ix;
$foo = qr/ quantity: \s* $number /ix;

My actual regular expression is many lines and does two-digit and ordinal numbers (e.g., "twenty-two", "forty-fourth" and "twelve are all complete matches), and I use it in several places. This expression compiles fast, but it is certainly non-trivial. I prefer to compile it once and then add it to other regular expressions, as Perl allows.

Is there a way to nest regular expressions in this manner in Python?

1
  • If you're trying to solve readability of your regex, also check out re.VERBOSE. amk.ca/python/howto/regex/… Commented Dec 17, 2009 at 15:17

2 Answers 2

7

In python, you build regular expressions by passing a string to re.compile. You can "nest" regular expression by just doing regular string manipulation:

#!/usr/bin/env python
import re
number = 'zero | one | two | three | four | five | six | seven | eight | nine'
foo = re.compile(' quantity: \s* (%s) '%number,re.VERBOSE|re.IGNORECASE)
teststr=' quantity:    five '
print(foo.findall(teststr))
# ['five']
Sign up to request clarification or add additional context in comments.

Comments

2

This is probably not quite the same. But you could do this:

import re
number = "(?:zero | one | two | three | four | five | six | seven | eight | nine)"
foo = "quantity: \s* " + number
bar = re.compile(foo, re.I | re.X)

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.