在python中嵌套正则表达式 [英] nested regular expressions in python

查看:175
本文介绍了在python中嵌套正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在perl中我可以这样做:

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;

我的实际正则表达式是很多行,并且有两位数和数字(例如两个,四十四和十二都是完整的匹配),我在几个地方使用它,这个表达式编译速度很快,但它肯定是不重要的,我更喜欢编译一次,然后添加到其他正如Perl所说,正则表达式。

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.

有没有办法在Python中以这种方式嵌套正则表达式?

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

推荐答案

在python中,通过将一个字符串传递给re.compile来构建正则表达式
您可以通过执行常规字符串操作嵌套正则表达式:

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

这篇关于在python中嵌套正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆