Dell
Dell

Reputation: 19

Regular expression that accepts mm/yyyy and mm/dd/yyyy format

I have a regular expression which accepts date in mm/dd/yyyy format:

 /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;

How to I change it so that it accepts date in mm/yyyy format too?

I've tried:

/^(\d{1,2})\/(\d{0,2})\/(\d{4})$/;

but I can't get rid of the extra bracket.

Upvotes: 0

Views: 43

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

You can use modifier ? to make /dd optional:

/^(\d{1,2})(?:\/(\d{1,2}))?\/(\d{4})$/;

Upvotes: 1

Related Questions