NoStressDeveloper
NoStressDeveloper

Reputation: 533

RegEx to Match MM/YYYY

I have ^((0[1-9])|(1[0-2]))\/(\d{4})$ to match MM/YYYY.

However, it does not match 9/2015.

What do I have to change to make it match 9/2015 in addition to 09/2015?

Upvotes: 1

Views: 77

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You need to make the zero optional and get rid of the unnecessary capture groups:

^(0?[1-9]|1[0-2])/\d{4}$
   ^

See regex demo

Note that the ? quantifier meaning is match the preceding subpattern 0 or more times. Thus, the 0 will be either matched once or an empty string will do for the regex engine.

See Quantifiers in Regular Expressions for more details on quantifiers in regular expressions.

Upvotes: 1

ideafixxxer
ideafixxxer

Reputation: 474

Put a question mark after 0

^((0?[1-9])|(1[0-2]))\/(\d{4})$

Upvotes: 2

CollinD
CollinD

Reputation: 7573

It will not take 9/2015 because that does not match your format MM/YYYY If you want to match M/YYYY OR MM/YYYY you should use something like this

^(0[1-9]|1[0-2]|[1-9])/(\d{4})$

Upvotes: 1

Related Questions