Regular Expression Match to test for a valid year

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

    You need to add a start anchor ^ as:

    ^\d{4}$
    

    Your regex \d{4}$ will match strings that end with 4 digits. So input like -1234 will be accepted.

    By adding the start anchor you match only those strings that begin and end with 4 digits, which effectively means they must contain only 4 digits.

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

    You can also use this one.

    ([0-2][0-9]|3[0-1])\/([0-1][0-2])\/(19[789]\d|20[01]\d)
    
    0 讨论(0)
提交回复
热议问题