Regular Expression to match a valid day in a date

后端 未结 10 1703
别那么骄傲
别那么骄傲 2020-12-11 01:45

I need help coming up with a regex to make sure the user enters a valid date The string will be in the format of mm/dd/yyyy

Here is what I have come up

相关标签:
10条回答
  • 2020-12-11 02:10

    Regex for 0-31:

    (0[1-9]|[12]\d|3[01])
    

    Or if you don't want days with a preceding zero (e.g. 05):

    ([1-9]|[12]\d|3[01])
    
    0 讨论(0)
  • 2020-12-11 02:12

    Regex for 0-31 day:

    0[1-9]|[12]\d|3[01]) without prefix 0 - when "1", "23"...

    ([1-9]|[12]\d|3[01]) with prefix 0 - when "01", "04"

    (0?[1-9]|[12]\d|3[01]) - with or without "0" - when ""

    0 讨论(0)
  • 2020-12-11 02:14

    Simpler regex:

    ([12]\d|3[01]|0?[1-9])
    

    Consider the accepted answer and this expression:

    (0[1-9]|[12]\d|3[01])
    

    This matches 01 but not 1

    The other expression in the accepted answer:

    ([1-9]|[12]\d|3[01])
    

    This matches 1 but not 01

    It is not possible to add an OR clause to get them both working.

    The one I suggested matches both. Hope this helps.

    0 讨论(0)
  • 2020-12-11 02:15

    Is regular expression a must? If not, you better off using a different approach, such as DateTime::Format::DateManip

    my @dates = (
        '04/23/2009',
        '01/22/2010 6pm',
        'adasdas',
        '1010101/12312312/1232132'
    );
    
    for my $date ( @dates ) 
    {
        my $date = DateTime::Format::DateManip->parse_datetime( $date );
        die "Bad Date $date"  unless (defined $date);
        print "$dt\n";
    }
    
    0 讨论(0)
  • 2020-12-11 02:17

    Try it:
    /(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/((19|20)\d\d)/

    0 讨论(0)
  • 2020-12-11 02:22

    This isn't all that hard...

    qr#^
        (?: 0[1-9] | 1[012] )
        /
        (?:
            0[1-9] | 1[0-9] | 2[0-8]
            | (?<! 0[2469]/ | 11/ ) 31
            | (?<! 02/ ) 30
            | (?<! 02/
                 (?= ... 
                     (?: 
                         .. (?: [02468][1235679] | [13579][01345789] )
                         | (?: [02468][1235679] | [13579][01345789] ) 00
                     )
                 )
            ) 29
        )
        /
        [0-9]{4}
        \z
    #x
    
    0 讨论(0)
提交回复
热议问题