Regular Expression to match a valid day in a date

后端 未结 10 1734
别那么骄傲
别那么骄傲 2020-12-11 01:45

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

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 02:27

    • As many have noted above, if we want to validate the date as a whole then a RegEx is a very poor choice.
    • But if we want to match a pattern of numbers, in this case from 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.

      • Test: gawk 'BEGIN{ for(i=0;i<=32;i++){ if (i ~ /^([0-2]?[1-9]|3[01])$/){print i " yes"}else {print i " no"} } }
      • This can be corrected as follows: ^([0-2]?[1-9]|3[01]|10|20)$

    So kindly consider the following solution...

    1. Identify the sets that need to be matched:

    • Days with prefix "0": {01,...,09},{10,...,31}
      • Sub-set {10,...,31} can be split into => {10,...,29},{30,31}
    • Without any prefix: {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]

提交回复
热议问题