Python中的可组合正则表达式

10 投票
2 回答
1951 浏览
提问于 2025-04-15 13:02

我经常想把简单的正则表达式组合成复杂的正则表达式。目前我知道的唯一方法就是通过字符串操作,比如:

Year = r'[12]\d{3}'
Month = r'Jan|Feb|Mar'
Day = r'\d{2}'
HourMins = r'\d{2}:\d{2}'

Date = r'%s %s, %s, %s' % (Month, Day, Year, HourMins)
DateR = re.compile(Date)

有没有人知道在Python中有没有其他方法或者更系统的方式(可能是某个模块)来组合正则表达式?我更希望能单独编译每个正则表达式(比如为了使用不同的编译选项),但这样一来似乎就没有办法再组合它们了!?

2 个回答

4

你可以使用Python的格式化语法来实现这个:

types = {
    "year":           r'[12]\d{3}',
    "month":        r'(Jan|Feb|Mar)',
    "day":            r'\d{2}',
    "hourmins":    r'\d{2}:\d{2}',
}
import re
Date = r'%(month)s %(day)s, %(year)s, %(hourmins)s' % types
DateR = re.compile(Date)

(注意这里对Jan|Feb|Mar进行了分组处理。)

2

你可以使用Ping的rxb工具:

year = member("1", "2") + digit*3
month = either("Jan", "Feb", "Mar")
day = digit*2
hour_mins = digit*2 + ":" + digit*2

date = month + " " + day + ", " + year + ", " + hour_mins

接下来,你可以直接对得到的日期进行匹配,或者使用

DateR = date.compile()

撰写回答