繁体   English   中英

如何匹配三种格式的日期

[英]How to match three formats of dates

如何匹配 DD_MM_YYYY 和 MM_YYYY 以及 YYYY 格式的日期

我的弦其实是这样的

a-nice-text/22_10_2020.html

another-nice-text/10_2020.html

Just-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));

 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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM