【问题标题】:How to match date string to regular expression [duplicate]如何将日期字符串与正则表达式匹配[重复]
【发布时间】:2018-07-16 10:03:53
【问题描述】:

我正在尝试使用以下代码检查输入值是否与日期格式 YYYY-MM-DDYYYY-MM-DD - YYYY-MM-DD 匹配,但它在输入 2018-01-29 上返回 false。

  const singleDateRegex = new RegExp('\d{4}-\d{2}-\d{2}$');
  const rangeRegex = new RegExp('\d{4}-\d{2}-\d{2} \d{4}-\d{2}-\d{2}$');

  const matchSingle = singleDateRegex.test(value); //false
  const matchRange = rangeRegex.test(value);       //false

【问题讨论】:

  • 您可以测试您的正则表达式here。帮了我很多

标签: javascript regex typescript


【解决方案1】:

您必须转义 RegExp 构造函数中使用的\ (\\)。

为什么不使用正则表达式文字,它由斜线之间的模式组成:

const singleDateRegex = new RegExp(/\d{4}-\d{2}-\d{2}$/);
const rangeRegex = new RegExp(/\d{4}-\d{2}-\d{2}\s\d{4}-\d{2}-\d{2}$/);

console.log(singleDateRegex.test('2018-01-29'));
console.log(rangeRegex.test('2018-01-29 2018-01-29'));

【讨论】:

    猜你喜欢
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多