Regular Expression Match to test for a valid year

后端 未结 14 1535
清歌不尽
清歌不尽 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 02:58

    I use this regex in Java ^(0[1-9]|1[012])[/](0[1-9]|[12][0-9]|3[01])[/](19|[2-9][0-9])[0-9]{2}$

    Works from 1900 to 9999

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

    In theory the 4 digit option is right. But in practice it might be better to have 1900-2099 range.

    Additionally it need to be non-capturing group. Many comments and answers propose capturing grouping which is not proper IMHO. Because for matching it might work, but for extracting matches using regex it will extract 4 digit numbers and two digit (19 and 20) numbers also because of paranthesis.

    This will work for exact matching using non-capturing groups:

    (?:19|20)\d{2}

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

    you can go with sth like [^-]\d{4}$: you prevent the minus sign - to be before your 4 digits.
    you can also use ^\d{4}$ with ^ to catch the beginning of the string. It depends on your scenario actually...

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

    Years from 1000 to 2999

    ^[12][0-9]{3}$
    

    For 1900-2099

    ^(19|20)\d{2}$
    
    0 讨论(0)
  • 2020-11-29 03:02

    Use;

    ^(19|[2-9][0-9])\d{2}$ 
    

    for years 1900 - 9999.

    No need to worry for 9999 and onwards - A.I. will be doing all programming by then !!! Hehehehe

    You can test your regex at https://regex101.com/

    Also more info about non-capturing groups ( mentioned in one the comments above ) here http://www.manifold.net/doc/radian/why_do_non-capture_groups_exist_.htm

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

    If you need to match YYYY or YYYYMMDD you can use:

    ^((?:(?:(?:(?:(?:[1-9]\d)(?:0[48]|[2468][048]|[13579][26])|(?:(?:[2468][048]|[13579][26])00))(?:0?2(?:29)))|(?:(?:[1-9]\d{3})(?:(?:(?:0?[13578]|1[02])(?:31))|(?:(?:0?[13-9]|1[0-2])(?:29|30))|(?:(?:0?[1-9])|(?:1[0-2]))(?:0?[1-9]|1\d|2[0-8])))))|(?:19|20)\d{2})$
    
    0 讨论(0)
提交回复
热议问题