我对正则表达式非常不熟悉,所以我不知道从哪里开始。我需要在文件中存储时间范围值。我想在保存之前对正则表达式进行验证。
格式必须是:
00:00-00:00
其中数字的最小值可以是0,最大值可以表示为
23:59-23:59
如何确保字符串符合此约束?
答案 0 :(得分:0)
试试这个
\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