2016-04-14 51 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点半”等等,如果在一个正则表达式中可能的话。 –