views:

143

answers:

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?

+3  A: 

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']
unutbu
A: 

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)
Gumbo