aggicd
aggicd

Reputation: 737

REGEX for 2 date formats

I want to allow 2 different date formats:

1/1/2017 and 1-JAN-2017

I am using this regex but its not working:

re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})|[0-9]{1,2}\-[a-zA-Z]{3}\-[0-9]{4}/;

Upvotes: 1

Views: 45

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

Group the alternatives and add the end of string anchor:

re = /^(?:\d{1,2}\/\d{1,2}\/\d{4}|\d{1,2}-[a-zA-Z]{3}-\d{4})$/;
       ^^^                       ^                         ^^

See the regex demo.

Without the grouping construct, the ^ is only applied to (\d{1,2}), and the other alternative is searched for at any position in the string.

Without the $ anchor, the pattern can match even if the pattern found is not at the end of the string (and you will get partial matches).

Upvotes: 5

Related Questions