Regular Expression Match to test for a valid year

后端 未结 14 1498
清歌不尽
清歌不尽 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:05

    This works for 1900 to 2099:

    /(?:(?:19|20)[0-9]{2})/
    
    0 讨论(0)
  • 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*$
    
    0 讨论(0)
  • 2020-11-29 03:11

    /^\d{4}$/ This will check if a string consists of only 4 numbers. In this scenario, to input a year 989, you can give 0989 instead.

    0 讨论(0)
  • 2020-11-29 03:14

    You could convert your integer into a string. As the minus sign will not match the digits, you will have no negative years.

    0 讨论(0)
  • 2020-11-29 03:19

    To test a year in a string which contains other words along with the year you can use the following regex: \b\d{4}\b

    0 讨论(0)
  • 2020-11-29 03:20

    Building on @r92 answer, for years 1970-2019:

    (19[789]\d|20[01]\d)
    
    0 讨论(0)
提交回复
热议问题