Python - 不匹配的正则表达式

0 投票
1 回答
616 浏览
提问于 2025-04-16 05:54

我有一个正则表达式:

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

我用它来处理赛马的状态字符串。有时候,一匹马的状态可能看起来像这样 "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

1 个回答

0

这个可以用:

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

撰写回答