ddeamaral
ddeamaral

Reputation: 1443

Regular Expression to match MM/YYYY or m/YYYYY

I would like to see a regular expression that matches the following date formats.

1/2017
01/2017
12/2017

Here is what I have so far, however it only matches the last two. What am I missing?

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

I also don't want it to match at all if the format is 12/1/2017 (MM/dd/yyyy or dd/MM/yyyy)

Thanks,

Upvotes: 3

Views: 3074

Answers (3)

Rahul Desai
Rahul Desai

Reputation: 15501

Make the 0 optional by adding ? next to the 0 in your regex.

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

Regex101 demo

EDIT: Surround the above regex with \b (border) so it does not match 5/21/2017 at all.

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

Updated Regex101 demo

EDIT 2: Updated regex as per Glenn's comment:

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

Updated Regex101 demo

Upvotes: 3

leoap
leoap

Reputation: 1729

This regex:

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

Will match:

1/2017
01/2017
12/2017

But will not match:

12/1/2017
13/2017
111/2017
/2017

The modifier g is for global.

The modifier m is for multi-line, which makes possible the use of ^ and $ to delimiter an start and end.

https://regex101.com/r/ompmyK/3

Upvotes: 1

ganesshkumar
ganesshkumar

Reputation: 1377

((0?[1-9])|(1[0-2]))\/(\d{4}). The first input doesn't have 0. Adding + will match zero or one occurrence of 0

Upvotes: 3

Related Questions