How to match three formats of dates

Viewed 66

How do i match dates in format DD_MM_YYYY and MM_YYYY and also YYYY

My strings are actually like these

a-nice-text/22_10_2020.html

another-nice-text/10_2020.html

Just-another-text/2020.html

I'm currently doing this:

str.match(/\d{2}_\d{2}_\d{4}\.html/)

but it's only matching string with 22_10_2020.html

2 Answers

You can make the \d{2}_ optional with the ? character:

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


You can also use ?: to prevent capturing the groups:

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

Related