Reputation: 1443
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
Reputation: 15501
Make the 0
optional by adding ?
next to the 0
in your regex.
((0?[1-9])|(1[0-2]))\/(\d{4})
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
EDIT 2: Updated regex as per Glenn's comment:
(?:^|[^\/\d])\K(?:0?[1-9]|1[0-2])\/\d{4}\b
Upvotes: 3
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
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