在字符串中使用正则表达式查找日期

时间:2017-11-22 02:22:58

标签: javascript regex

我试图创建一个函数来验证字符串中是否有有效日期(YYYY-MM-DD),然后作为函数的结果返回它。

到目前为止,我有这个:

function findDate(str){
   let dateReg = /^(19[7-9]\d|20[0-1][0-7])\/(0[1-9]|1[0-2])\/([0-2][1-9]|3[0-1])$/;
   let matchingDate = [];
   let strSplit = str.split(' ');

    for(let i = 0; i < strSplit.length; i++){
      if(dateReg.test(strSplit[i])){
        matchingDate.push(strSplit[i]);
      } else {
        return 'No valid date';
      }
    }

    return matchingDate;

}

findDate('I was born on 2017/12/05 ok?');
// findDate('She was born on 1960/08/31 ok?');
// findDate('He was born on 2010/15/31 ok?');

知道我错过了什么吗?默认情况下,它会跳过测试部分。

谢谢!

2 个答案:

答案 0 :(得分:1)

那是因为只要遇到不是有效日期的字符串(根据你的正则表达式),你就会立即返回该函数。试试这个

&#13;
&#13;
function findDate(str){
   let dateReg = /^(19[7-9]\d|20[0-1][0-7])\/(0[1-9]|1[0-2])\/([0-2][1-9]|3[0-1])$/;
   let matchingDate = [];
   let strSplit = str.split(' ');

   for(let i = 0; i < strSplit.length; i++){
     if(dateReg.test(strSplit[i])){
        matchingDate.push(strSplit[i]);
     } 
   }
   return matchingDate.length == 0 ? 'No valid date' : matchingDate;

}

findDate('I was born on 2017/12/05 ok?');
&#13;
&#13;
&#13;

答案 1 :(得分:0)

根据Pratansyah's answer,只要任何一个单词与正则表达式匹配,您的当前代码就会从函数返回。

但请注意,您不需要拆分字符串并单独测试单词,您可以使用string .match() method搜索整个字符串,从而大幅缩小您的功能:

&#13;
&#13;
function findDate(str){
   let dateReg = /\b(19[7-9]\d|20[0-1][0-7])\/(0[1-9]|1[0-2])\/([0-2][1-9]|3[0-1])\b/g;
   return str.match(dateReg) || 'No valid date';
}

console.log(findDate('I was born on 2017/12/05 ok?'));
console.log(findDate('She was born on 1960/08/31 ok?')); // doesn't match
console.log(findDate('He was born on 2010/15/31 ok?'));  // doesn't match
console.log(findDate('He was born 2010/12/31, and she was born 2011/11/02, ok?'));
&#13;
&#13;
&#13;

请注意,要与.match()这样使用,正则表达式应该^$,否则它只会在字符串只包含日期时匹配,但您可能希望\b代替字边界。如果将g标志添加到正则表达式,它将在字符串中找到所有匹配的日期。

如果没有匹配,则.match()会返回null,因此我已使用||运算符默认为'No valid date'消息。< / p>

(请注意,这并非实际验证日期,因为它假设所有月份都可以有31天,因此它将接受2017/02/31。)