Regular Expression to match valid dates

后端 未结 15 2010
庸人自扰
庸人自扰 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:07

    Maintainable Perl 5.10 version

    /
      (?:
          (? (?&mon_29)) [\/] (?(?&day_29))
        | (? (?&mon_30)) [\/] (?(?&day_30))
        | (? (?&mon_31)) [\/] (?(?&day_31))
      )
      [\/]
      (? [0-9]{4})
      
      (?(DEFINE)
        (? 0?2 )
        (? 0?[469]   | (11) )
        (? 0?[13578] | 1[02] )
    
        (? 0?[1-9] | [1-2]?[0-9] )
        (? 0?[1-9] | [1-2]?[0-9] | 30 )
        (? 0?[1-9] | [1-2]?[0-9] | 3[01] )
      )
    /x
    

    You can retrieve the elements by name in this version.

    say "Month=$+{month} Day=$+{day} Year=$+{year}";
    

    ( No attempt has been made to restrict the values for the year. )

提交回复
热议问题