gpt4 book ai didi

javascript - 如何匹配三种格式的日期

转载 作者:行者123 更新时间:2023-12-01 15:39:49 25 4
gpt4 key购买 nike

我如何匹配 DD_MM_YYYY 和 MM_YYYY 以及 YYYY 格式的日期
我的弦其实是这样的a-nice-text/22_10_2020.htmlanother-nice-text/10_2020.htmlJust-another-text/2020.html我目前正在这样做:str.match(/\d{2}_\d{2}_\d{4}\.html/)但它仅与 22_10_2020.html 匹配字符串

最佳答案

您可以制作 \d{2}_可选 ?特点:

const regex = /(\d{2}_)?(\d{2}_)?\d{4}\.html/;

console.log('01_01_2020.html'.match(regex));
console.log('01_2020.html'.match(regex));
console.log('2020.html'.match(regex));
console.log('abc.html'.match(regex));


您也可以使用 ?:防止捕获组:

const regex = /(?:\d{2}_)?(?:\d{2}_)?\d{4}\.html/;

console.log('01_01_2020.html'.match(regex));
console.log('01_2020.html'.match(regex));
console.log('2020.html'.match(regex));
console.log('abc.html'.match(regex));

关于javascript - 如何匹配三种格式的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62863399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com