简体   繁体   English

正则表达式匹配时间范围

[英]Regexp matching time ranges

I am trying to create a regular expression for parsing and validation of time ranges in Javascript. 我正在尝试创建一个正则表达式来解析和验证Javascript中的时间范围。 Keep in mind that I am simply looking to parse correctly structured strings of characters. 请记住,我只是想解析正确构造的字符串。 The validation logic regarding the time ranges is made afterward 随后进行关于时间范围的验证逻辑

Requirements: 要求:

  1. Time elements are expressed always in 24 hour and should be of (HH:mm) format. 时间元素始终以24小时表示,并且应采用(HH:mm)格式。
  2. Time range is defined as 2 time elements separated by a dash 时间范围定义为2个时间元素,以短划线分隔
  3. String should at least have one timerange or more separated by comma 字符串至少应具有一个或多个时间范围,并以逗号分隔
  4. Matching pattern should tolerate spaces between elements 匹配模式应允许元素之间的间隔
  5. The validated string should either match as a whole or completely fail to match 经过验证的字符串应该整体匹配,或者完全不匹配

What I came up is the following: 我想到的是以下内容:

/((?:[01]\d:[0-5][0-9]|2[0-3]:[0-5][0-9])(?:\s?)-(?:\s?)(?:[01]\d:[0-5][0-9]|2[0-3]:[0-5][0-9])(?:\s?,\s?)?)/g

which seems to satisfy all the rules apart from rule 5. ie. 这似乎满足除规则5之外的所有规则。 if incorrect characters exist they simply not match but the expression does not fail as a whole 如果存在不正确的字符,则它们根本不匹配,但整个表达式不会失败

is there any way to embed rule 5 inside this regex? 有什么办法可以将规则5嵌入此正则表达式中?

Add the anchors to mark start and end of string: 添加锚点以标记字符串的开始和结束:

^((?:[01]\\d:[0-5][0-9]|2[0-3]:[0-5][0-9])(?:\\s?)-(?:\\s?)(?:[01]\\d:[0-5][0-9]|2[0-3]:[0-5][0-9])(?:\\s?,\\s?)?)+$ ( demo ) ^((?:[01]\\d:[0-5][0-9]|2[0-3]:[0-5][0-9])(?:\\s?)-(?:\\s?)(?:[01]\\d:[0-5][0-9]|2[0-3]:[0-5][0-9])(?:\\s?,\\s?)?)+$演示

Then, grab the whole match, and then split by , . 然后,抓住整个比赛,然后将,分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM