I need help coming up with a regex to make sure the user enters a valid date
The string will be in the format of mm/dd/yyyy
Here is what I have come up
01-31
then RegEx is fine so long as there is some backend logic that validates the date as a whole, if so desired.I see the expected answer currently fails for 10, 20.
gawk 'BEGIN{ for(i=0;i<=32;i++){ if (i ~ /^([0-2]?[1-9]|3[01])$/){print i " yes"}else {print i " no"} } }
^([0-2]?[1-9]|3[01]|10|20)$
So kindly consider the following solution...
1. Identify the sets that need to be matched:
{01,...,09},{10,...,31}
{10,...,31}
can be split into => {10,...,29},{30,31}
{1,...,31} => {1,...,9},{10,...,31}
2. Corresponding regular expressions for each sub-set:
---------------------------------
Sub-Set | Regular-Expression
---------------------------------
{01,...,09} | [0][1-9]
{10,...,29} | [1-2][0-9]
{30,31} | 3[01]
{1,...,9} | [1-9]
---------------------------------
Now we can group ([0][1-9])
and ([1-9])
together as ([0]?[1-9])
. Where ?
signifies 0 or 1 occurrences of the pattern/symbol. [UPDATE] - Thank you @MattFrear for pointing it out.
So the resulting RegEx is: ^(([0]?[1-9])|([1-2][0-9])|(3[01]))$
Tested here: http://regexr.com/?383k1 [UPDATE]