Regular Expression to match valid dates

后端 未结 15 1828
庸人自扰
庸人自扰 2020-11-22 04:48

I\'m trying to write a regular expression that validates a date. The regex needs to match the following

  • M/D/YYYY
  • MM/DD/YYYY
  • Single digit mon
15条回答
  •  长情又很酷
    2020-11-22 05:04

    Perl expanded version

    Note use of /x modifier.

    /^(
          (
            ( # 31 day months
                (0[13578])
              | ([13578])
              | (1[02])
            )
            [\/]
            (
                ([1-9])
              | ([0-2][0-9])
              | (3[01])
            )
          )
        | (
            ( # 30 day months
                (0[469])
              | ([469])
              | (11)
            )
            [\/]
            (
                ([1-9])
              | ([0-2][0-9])
              | (30)
            )
          )
        | ( # 29 day month (Feb)
            (2|02)
            [\/]
            (
                ([1-9])
              | ([0-2][0-9])
            )
          )
        )
        [\/]
        # year
        \d{4}$
      
      | ^\d{4}$ # year only
    /x
    

    Original

    ^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$
    

提交回复
热议问题