2010-10-22 150 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