12小时时间戳的正则表达式以及对时间的支持

时间:2016-04-14 12:16:54

标签: regex time

试图让这个正则表达式正常工作,但似乎无法做到。

我需要正则表达式来基本上选择这些时间组合:

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))?

感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分: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 -