OmniOwl
OmniOwl

Reputation: 5709

Capture up to three different kinds of dates?

I have this RegEx here

^([12]\d{3})(?:[.](10|11|12|(?:0[1-9]))(?:[.](30|31|(?:0[1-9])|(?:[12]\d)))?)?$

The purpose being to capture either: yyyy, yyyy.mm or yyyy.mm.dd as valid date strings for an input field. It does this fine, however, turns out it needs to be the other way around.

I have tried to reverse the process but I keep coming up short and can't quite figure it out. How would I make it capture: yyyy, mm.yyyy or dd.mm.yyyy as valid date strings?

(Should be mentioned that regex is essentially magic to me. I don't really get it intuitively.)

Upvotes: 0

Views: 43

Answers (1)

Astor Bizard
Astor Bizard

Reputation: 315

As pointed out in the comments, it is better to check for date validity with other tools than regular expressions. I would suggest to use the following regex:
^((\d{2})\.)?((\d{2})\.)?(\d{4})$
where the 2nd, 4th and 5th capturing groups will correspond to respectively dd, mm and yyyy.

You can check the validity of these values afterwards.

If you still want to do it entirely with one regex, you can go with the following:
^((30|31|[012]\d)\.)?((11|12|0\d)\.)?(\d{4})$
but it still doesn't cover the February 29th problem, nor the matching of 30/31 days months.

Upvotes: 1

Related Questions