Regex日期验证yyyy-mm-dd返回null Javascript



我正在使用js测试我的regex验证器,我已经在tester中测试了regex,它是有效的,但我认为问题出在我的代码上,我对js还很陌生。希望有人能在这件事上帮我。谢谢

这是我使用的输入字符串,然后我将返回的值标记为每个字符串——它是有效的yyyy-mm-dd格式,以检查它是否是日期。

project = "HRT: Human Resource Ticketing" AND (("Time to first response" = breached() OR "Time to resolution" = breached()) AND resolution = Done AND "Request Type" = "Payroll Dispute (HR)") AND (createdDate >= 2022-10-1 AND createdDate  <= 2022-10-31)
const items = token.split(" ");
for (const item of items) {
console.log(item.match("([12]d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]d|3[01]))"))
}

我不知道为什么它会返回null,顺便说一句,我只需要捕捉日期,这样我就可以用我想要的任何东西替换日期。谢谢

只需将字符串""更改为正则表达式//。将"([12]d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]d|3[01]))"改为:/([12]d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]d|3[01]))/

例如,它应该返回以下数组:

[
'2022-10-31',
'2022-10-31',
'10',
'31',
index: 0,
input: '2022-10-31)',
groups: undefined
]

您可以通过item[0]访问匹配的值。

因此,新代码如下:

const token = `HRT: Human Resource Ticketing" AND (("Time to first response" = breached() OR "Time to resolution" = breached()) AND resolution = Done AND "Request Type" = "Payroll Dispute (HR)") AND (createdDate >= 2022-10-1 AND createdDate  <= 2022-10-31)`
const regex = /([12]d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]d|3[01]))/
const items = token.split(" ");
for (const item of items) {
const match = item.match(regex)
if (match) console.log(match[0])
}

最新更新