在数组中查找多个正则表达式

时间:2018-07-13 06:41:59

标签: javascript regex

我有一个包含各种时隙的数组:

var timeArray = ["00:05 - 02:50", "03:05 - 05:50", "05:10 - 07:55", "06:25 - 09:10", "07:55 - 10:40", "09:00 - 11:45", "15:10 - 17:55", "17:05 - 19:45", "18:50 - 21:35", "19:40 - 22:25", "20:45 - 23:40", "22:00 - 00:45", "22:40 - 01:25", "11:55 - 16:15"]

我想搜索06-12之间的所有时隙,并将它们推送到数组中。我在js下面编写了代码,但这返回了一个空数组:

var resultArray = new Array();
for (var i = 0; i < timeArray.length; i++) {
    var bar = /^06:^07:^08:^09:^10:^11/;
    if (bar.test(timeArray[i])) {
        alert("found desired timeslots");
        resultArray.push(timeArray[i]);
    }
};

2 个答案:

答案 0 :(得分:3)

您可以将一些组用于所需时间,并且仅使用一个开始指示器。

var timeArray = ["00:05 - 02:50", "03:05 - 05:50", "05:10 - 07:55", "06:25 - 09:10", "07:55 - 10:40", "09:00 - 11:45", "15:10 - 17:55", "17:05 - 19:45", "18:50 - 21:35", "19:40 - 22:25", "20:45 - 23:40", "22:00 - 00:45", "22:40 - 01:25", "11:55 - 16:15"],
    resultArray = timeArray.filter(s => /^(0[6-9]|1(0|1))/.test(s));

console.log(resultArray);

答案 1 :(得分:1)

正则表达式应为:^06|^07|^08|^09|^10|^11。另一个更简洁的选择是:/^0[6-9]|^1[01]/

以下可运行示例:

var timeArray = ["00:05 - 02:50", "03:05 - 05:50", "05:10 - 07:55", "06:25 - 09:10", "07:55 - 10:40", "09:00 - 11:45", "15:10 - 17:55", "17:05 - 19:45", "18:50 - 21:35", "19:40 - 22:25", "20:45 - 23:40", "22:00 - 00:45", "22:40 - 01:25", "11:55 - 16:15"]

var resultArray = new Array();
for (var i = 0; i < timeArray.length; i++) {
  var bar = /^06|^07|^08|^09|^10|^11/;
  if (bar.test(timeArray[i])) {
    console.log("found desired timeslots: " + timeArray[i]);
    resultArray.push(timeArray[i]);
  }
};