Home > Mobile >  regular expression date range format dmY
regular expression date range format dmY

Time:04-15

I should wrote a regular expression to calculate/validate range date from date format 01012022 to 31032022 (from January to March 2022). Can you help me, please?

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

CodePudding user response:

You can structure it into two parts.

Match on Jan and Mar (as they both have 31 days):

  • 0[1-9] matches days from 01 to 09
  • [12][0-9] matches days from 10 to 29
  • 3[01] matches days from 30 to 31
  • 0[13] matches month 01 and 03

Match on Feb:

  • 0[1-9] matches days from 01 to 09
  • 1[0-9] matches days from 10 to 19
  • 2[0-9] matches days from 20 to 29
  • 02matches month 02

For both: 2022 matches year 2022.

Here's the complete regex:

"(((0[1-9]|[12][0-9]|3[01])0[13])|(0[1-9]|1[0-9]|2[0-9])02)(2022)"
  • Related