2016-03-22 72 views
1

我困在一個正則表達式操作中。我想寫一個可選的表達式找到日期字符串可選的正則表達式操作

我有三根弦A,B和C如下

a = '(sam was born on 11 Oct 1990)' 
b = 'sam was born on Oct 1990' 
c = 'sam was born on 1990' 

給我想寫的表達,從而爲

a I get output '11 Oct 1990' 
b I get output 'Oct 1990' 
c I get output '1990' 

我能夠爲a和b獲取正確的輸出,但對於c我無法。但是,當我改變c爲

c = 'sam was born on 1990' -- with two spaces between on and 1990 

我獲取正確的輸出。我用

的正則表達式是:

print re.findall(r"((11)?[\s\(](((Nov|Oct))?([\s\(-]|,\s)(1990|1991)))", a) 

我取的輸出是:

Output for a : [('11 Oct 1990', '11', 'Oct 1990', 'Oct', 'Oct', ' ', '1990')] 
Ouptut for b : [(' Oct 1990', '', 'Oct 1990', 'Oct', 'Oct', ' ', '1990')] 
Ouptut for c : [] 

任何幫助,將不勝感激。謝謝

+1

看看有助於你設計正則表達式的網站,例如regex101.com – asimoneau

+0

不要浪費你的時間在線正則表達式網站,特別是regexr.com和regex101.com。他們臃腫,緩慢,並加載錯誤。 – sln

回答

1

您可以使用此:

regex = re.compile(r'((?:11)?[\s\(](?:(?:(?:Nov|Oct))?(?:[\s\(?:-]|,\s)?(?:1990|1991)))') 

這只是你的一樣,但與非捕獲塊,僅外一個捕獲

+0

謝謝,,,,,很多.. – Sam

0

在日期之前您不需要\s。這給你你想要的輸出。

print re.findall(r"((11)?[\s\(](((Nov|Oct))?([\s\(-]|)(1990|1991)))", c) 
+0

嗨Borja,感謝你的迴應,我給了(,\ s)來處理像(薩姆出生於1990年10月11日),我們有一個逗號之後10月 – Sam

+0

你沒有在帖子中指定。在你的任何輸入中都沒有昏迷。 –

0

另一種方法(可能更簡單?):

on\s([^)\n]+)\)?$ 
# match on literally 
# a whitespace 
# followed by anything NOT a closing parenthesis or newline (save this to Group 1) 
# followed by an optional parenthesis 
# bind the Expression to the end of the line 

這考慮到之前的on和可選的)在期望的匹配之後。您需要使用multiline模式,請參閱working on regex101.com

0

請看如果這個工程:

str=re.findall(r'([\d]{0,2}\s*?[a-zA-Z]*?\s*[\d]{4}',a) 
0

我覺得這是一個很好的和明確的選擇:

found = re.findall(r"(11\s)?(Nov\s|Oct\s)?(1990|1991)", a) 

然後,如果你有字符串你可以打印多個日期:

for date in found: 
    print ''.join(date)