Regular Expression Match to test for a valid year

后端 未结 14 1808
清歌不尽
清歌不尽 2020-11-29 02:27

Given a value I want to validate it to check if it is a valid year. My criteria is simple where the value should be an integer with 4 characters. I know this is

14条回答
  •  天涯浪人
    2020-11-29 03:11

    The "accepted" answer to this question is both incorrect and myopic.

    It is incorrect in that it will match strings like 0001, which is not a valid year.

    It is myopic in that it will not match any values above 9999. Have we already forgotten the lessons of Y2K? Instead, use the regular expression:

    ^[1-9]\d{3,}$
    

    If you need to match years in the past, in addition to years in the future, you could use this regular expression to match any positive integer:

    ^[1-9]\d*$
    

    Even if you don't expect dates from the past, you may want to use this regular expression anyway, just in case someone invents a time machine and wants to take your software back with them.

    Note: This regular expression will match all years, including those before the year 1, since they are typically represented with a BC designation instead of a negative integer. Of course, this convention could change over the next few millennia, so your best option is to match any integer—positive or negative—with the following regular expression:

    ^-?[1-9]\d*$
    

提交回复
热议问题