Piyush Gulati
Piyush Gulati

Reputation: 23

RegEx not matching date

Why does the date RegEx:

^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$

Does not match 1999/01-01?

Can't figure this out. Is it because of delimiters?

Upvotes: 0

Views: 917

Answers (1)

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

This regex uses a reference to the second captured group using \2. Your second captured group is:

^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$*
            ^^^^^^^^

Which is the delimiter of your date, it could be any of the following - /.. As of now, your second delimiter have to be the same than the first one (because of the reference to the second capturing group) and that's why you can't match string of the format xxxxZxxYxx if Z != Y.

If you want such case to be matched, you can change your regex to:

^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$*

But note that if this is a sort of correct regex to find a date in the range 1900-2099, this will not allow you to test if the date is correct or not (it doesn't check the correct pairing of days number with month, ie: you can have 31 days in February).

Upvotes: 1

Related Questions