【问题标题】:Python - Non-matching regexPython - 不匹配的正则表达式
【发布时间】:2011-04-29 03:00:02
【问题描述】:

我有以下正则表达式:

regex = compile("((?P<lastyear>[\dBFUPR]+)/)*((?P<lastseason>[\dBFUPR]+))*(^|-(?P<thisseason>[\dBFUPR]*))")

我用来处理horce racing form strings。有时一匹马的形式看起来像这样“1234-”,这意味着它本赛季还没有参加比赛(“-”右侧没有数字)。

目前,我的正则表达式将匹配 thisseason 组中此类表单字符串末尾的“”。我不想要这种行为。在这种情况下,我希望该组为None。即

match = regex.match("1234-")
print match.group("thisseason") #None

示例

string = "1234/123-12"
match.group("lastyear") #1234
match.group("lastseason") #123
match.group("thisseason") #12

string = "00999F"
match.group("lastyear") #None
match.group("lastseason") #None
match.group("thisseason") #00999F

string = "12-3456"
match.group("lastyear") #None
match.group("lastseason") #12
match.group("thisseason") #3456

【问题讨论】:

    标签: python regex match


    【解决方案1】:

    这行得通:

    >>> regex = re.compile(r'(?:(?P<lastyear>[\dBFUPR]+)/)?(?:(?P<lastseason>[\dBFUPR]+)-)?(?P<thisseason>[\dBFUPR]+)?')
    >>> regex.match("1234/123-12").groupdict()
    {'thisseason': '12', 'lastyear': '1234', 'lastseason': '123'}
    >>> regex.match("00999F").groupdict()
    {'thisseason': '00999F', 'lastyear': None, 'lastseason': None}
    >>> regex.match("12-").groupdict()
    {'thisseason': None, 'lastyear': None, 'lastseason': '12'}
    >>> regex.match("12-3456").groupdict()
    {'thisseason': '3456', 'lastyear': None, 'lastseason': '12'}
    

    【讨论】:

    • 以上内容与“7463-”不匹配,这是不正确的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 2013-09-22
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 2022-12-11
    相关资源
    最近更新 更多