Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 367
ddeamaral Avatar asked Nov 19 '25 03:11

ddeamaral


2 Answers

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

like image 168
Rahul Desai Avatar answered Nov 20 '25 22:11

Rahul Desai


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

like image 32
ganesshkumar Avatar answered Nov 20 '25 20:11

ganesshkumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!