正则表达式允许MM:SS,TH或SS,TH

时间:2014-01-29 11:18:49

标签: javascript regex

我正在尝试编写一个正则表达式,允许以分钟,秒,十分之一和十分之一的时间输入时间。百分之一秒。 我遇到的问题是,用户也应该被允许在几秒钟内输入一个时间。十分之一秒,十分之一秒百分之一秒。变化是这样的:

MM:SS:第 米:SS:第 毫米:s:t中

你明白了。

以下允许ss:th | ss:t | s:th | s:t中

^(([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])(\.|\,)([0-9]|[0-9][0-9]))$

但是,只要我将分钟添加到表达式中,验证总是会失败:

^(([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])(\.|\,)([0-9]|[0-9][0-9])) | (([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])(\.|\,)([0-9]|[0-9][0-9]))$

最终我还需要添加小时数,并允许用户输入超过59秒的时间 - 例如67.32s

2 个答案:

答案 0 :(得分:1)

让我们现在坚持合法的价值观(以后总是可以放宽要求),让我们使用一个冗长的正则表达式,希望你的正则表达式支持那些:

^          # Start of string
(?:        # Match the following non-capturing group:
 (         # Match (and capture into group 1):
  \d{1,2}  # one or two digits
 )         # End of group 1
 :         # Match a colon
)?         # End of non-capturing group, make it optional.
(          # Start of capturing group 2:
 [0-5]?    # Match a number between 0 and 5 (optional)
 [0-9]     # Match a number between 0 and 9 (required)
)          # End of group 2
:          # Match a colon
([0-9])    # Match and capture a number (0-9) in group 3
(?:        # Match the following non-capturing group:
 ([0-9])   # Match and capture a number in group 4
)?         # End of non-capturing group (optional)
$          # End of string

live on regex101.com

编辑:JavaScript不支持详细的正则表达式,因此您需要:

/^(?:(\d{1,2}):)?([0-5]?[0-9]):([0-9])(?:([0-9]))?$/.test(subject)

如果subject符合要求,则获得真/假答案。

答案 1 :(得分:1)

以下未提及的格式可能不包括:)

^(?:\d+:)?(?:[0-5]\d:|[0-9]:)?(?:[0-5]\d|\d)(?:[.,]\d\d?)?$

成功并失败以下:

9.45  -  success
9  -  success
4:6.65  -  success
5:06.65  -  success
5:6,65  -  success
50:40  -  success
50:40.65  -  success
50:06.65  -  success
50:06.6  -  success
06.65  -  success
6.65  -  success
1:50:06.65  -  success
19:50:06.65  -  success
19:50:06.65  -  success
69,45  -  fail
69.45  -  fail
19:60:06.65  -  fail
19:50:96.65  -  fail

我会尽快输入解释。

修订 - 基于OP的评论

^(?:\d+:)?(?:[0-5]\d:|[0-9]:)?(?:[0-5]\d|\d|^\d\d)(?:[.,]\d\d?)?$

69,45|69.45之前失败的地方现在匹配。我刚刚在秒部分添加:

|^\d\d

当然,169,45会失败但只是将以前的添加内容更改为:

|^\d+

现在它将匹配任何数量的秒数:)