Search code examples
regex

How to match range of dates using regular expressions


I have, for example, this date range sentence to test: from 10-08-2024 to 12-08-2024, I need to extract the dates.

I have used Regex101 site to design the regular expressing, getting this one:

^(from)\s((?:0[1-9]|[12][0-9]|3[01])-(?:0[1-9]|1[1,2])-(?:19|20)\d{2})\s(to)\s((?:0[1-9]|[12][0-9]|3[01])-(?:0[1-9]|1[1,2])-(?:19|20)\d{2})$

It works, however, all are returned as groups instead of matches.

enter image description here

as you see, start and end dates are returned as groups. The only match is the whole sentence.

How can I get the dates to be returned as match 2 and match 3 instead of group 2 and group 4, respectively?

Thanks Jaime


Solution

  • You can use positive lookbehind to check (from|to) followed by the date regex that you have provided.

    (?<=(?:from|to)\s*)(?:(?:0[1-9]|[12][0-9]|3[01])-(?:0[1-9]|1[1,2])-(?:19|20)\d{2})
    

    Demo

    Here you get your dates as match 1 and match 2.

    Sample source:

    const regex = /(?<=(?:from|to)\s*)(?:(?:0[1-9]|[12][0-9]|3[01])-(?:0[1-9]|1[1,2])-(?:19|20)\d{2})/gm;
    
    const str = `from 10-08-2024 to 12-08-2024`;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
        m.forEach((match) => {
            console.log(match);
        });
    }