我对正则表达式非常不熟悉,所以我不知道从哪里开始。我需要将时间范围值存储在文件中。我想在保存之前根据正则表达式对其进行验证。
格式必须是:
00:00-00:00
其中数字的最小值可以为 0,最大值可以表示为
23:59-23:59
如何确保字符串与此约束匹配?
我对正则表达式非常不熟悉,所以我不知道从哪里开始。我需要将时间范围值存储在文件中。我想在保存之前根据正则表达式对其进行验证。
格式必须是:
00:00-00:00
其中数字的最小值可以为 0,最大值可以表示为
23:59-23:59
如何确保字符串与此约束匹配?
试试这个
\b((?:(?:[01][0-9]|2[0-3]):(?:[0-5][0-9]))-(?:(?:[01][0-9]|2[0-3]):(?:[0-5][0-9])))\b
解释
\b # Assert position at a word boundary
( # Match the regular expression below and capture its match into backreference number 1
(?: # Match the regular expression below
(?: # Match the regular expression below
# Match either the regular expression below (attempting the next alternative only if this one fails)
[01] # Match a single character present in the list “01”
[0-9] # Match a single character in the range between “0” and “9”
| # Or match regular expression number 2 below (the entire group fails if this one fails to match)
2 # Match the character “2” literally
[0-3] # Match a single character in the range between “0” and “3”
)
: # Match the character “:” literally
(?: # Match the regular expression below
[0-5] # Match a single character in the range between “0” and “5”
[0-9] # Match a single character in the range between “0” and “9”
)
)
- # Match the character “-” literally
(?: # Match the regular expression below
(?: # Match the regular expression below
# Match either the regular expression below (attempting the next alternative only if this one fails)
[01] # Match a single character present in the list “01”
[0-9] # Match a single character in the range between “0” and “9”
| # Or match regular expression number 2 below (the entire group fails if this one fails to match)
2 # Match the character “2” literally
[0-3] # Match a single character in the range between “0” and “3”
)
: # Match the character “:” literally
(?: # Match the regular expression below
[0-5] # Match a single character in the range between “0” and “5”
[0-9] # Match a single character in the range between “0” and “9”
)
)
)
\b # Assert position at a word boundary