2016-04-14 53 views
0

一直試圖讓這個正則表達式正常工作,但似乎無法做到。12小時時間戳的正則表達式以及對時間端點的支持

我需要的正則表達式基本回暖的時候,這些組合:

12am 
12:30am 
12am - 12pm 
12:30am - 1:30am 
12:30 - 1:30am 
12 - 1:30am 

如果我加入?在我的([a | p] m)部分後面,正則表達式將匹配我不想要的數字。

這裏是我的正則表達式代碼:

(?:(1[012]|[1-9]):([0-5][0-9])|(1[012]|[1-9])) ?([a|p]m)(?:\s-\s(?:(1[012]|[1-9]):([0-5][0-9])|(1[012]|[1-9])) ?([a|p]m))? 

任何幫助表示讚賞,謝謝。

+0

不會https://regex101.com/r/gN1qS7/3足夠? – rock321987

+0

您需要在某些地方添加'?'(參見[demo](https://regex101.com/r/cN7yK1/1))。 –

+0

@ rock321987這似乎是伎倆,但它仍然自己拾取「12」,我通過電子郵件內容運行此正則表達式,它將匹配一個日期,例如:「12二月」 –

回答

1

該做的工作:

((?:1[0-2]|\d)(?:\:[0-5]\d)?(?:[ap]m)?)[\s-]+((?:1[0-2]|\d)(?:\:[0-5]\d)?(?:[ap]m)?) 

Live Demo

解釋(第二組是相同的第一個):

1st Capturing group ((?:1[0-2]|\d)(?:\:[0-5]\d)?(?:[ap]m)) 

(?:1[0-2]|\d) Non-capturing group 
    1st Alternative: 1[0-2] 
     1 matches the character 1 literally 
     [0-2] match a single character present in the list below 
      0-2 a single character in the range between 0 and 2 
    2nd Alternative: \d 
     \d match a digit [0-9] 
(?:\:[0-5]\d)? Non-capturing group 
    Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy] 
    \: matches the character : literally 
    [0-5] match a single character present in the list below 
     0-5 a single character in the range between 0 and 5 
    \d match a digit [0-9] 
(?:[ap]m) Non-capturing group 
    [ap] match a single character present in the list below 
     ap a single character in the list ap literally (case insensitive) 
    m matches the character m literally (case insensitive) 

[\s-]+ match a single character present in the list below 

Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy] 
\s match any white space character [\r\n\t\f ] 
- the literal character - 
+0

我可能鍵入了這個愚蠢的,但我需要使用正則表達式12 - 1:30 pm拾取所有4個示例。 –

+0

@JohnnyDoey參見編輯 –

+0

我已經編輯了上面的帖子,更多的例子,我還要求正則表達式在「正午12點」以及「早上12點 - 凌晨1點半」等等,如果在一個正則表達式中可能的話。 –