【问题标题】:Composable Regexp in PythonPython中的可组合正则表达式
【发布时间】:2010-11-12 11:09:21
【问题描述】:

通常,我想从简单的正则表达式构建复杂的正则表达式。我目前知道这样做的唯一方法是通过字符串操作,例如:

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 中有一种不同的方法或更系统的方法(可能是一个模块)来拥有可组合的正则表达式?我宁愿单独编译每个正则表达式(例如,使用单独的编译选项),但似乎没有办法再组合它们了!?

【问题讨论】:

  • 您的操作方式看起来简洁明了。哦,顺便说一句,Date 变量不需要字符串中的“r”。
  • Python 是否允许在正则表达式中使用 cmets?
  • mmyers,是的。当您使用标志 re.VERBOSE 时,您可以将 # 用于 cmets。

标签: python regex


【解决方案1】:

您可以为此使用 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()
    

    【讨论】:

    • 这看起来像是我正在寻找的答案,谢谢。我将不得不检查模块如何处理编译选项和匹配组,但乍一看它看起来很完美:-)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多