Robert
Robert

Reputation: 21

nested regular expressions in python

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?

Upvotes: 2

Views: 7597

Answers (2)

Gumbo
Gumbo

Reputation: 655239

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)

Upvotes: 1

unutbu
unutbu

Reputation: 879561

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']

Upvotes: 6

Related Questions