2010-10-22 217 views
0

我有以下的正则表达式:Python的 - 非正则表达式匹配

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 

回答

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

以上不匹配 “7463-” 任何东西,这是不正确的。 – Peter 2010-10-22 13:19:25

+0

@Peter:现在查看我的编辑。 – SilentGhost 2010-10-22 14:06:58