How can I use a regular expression to validate month input?

前端 未结 9 822
孤街浪徒
孤街浪徒 2020-12-11 00:31

I am setting up this example Perl snippet to validate for months in a date:

Some scenarios I want to accept are:

MM M

#!/usr/bin/perl
use str         


        
相关标签:
9条回答
  • 2020-12-11 01:15

    Don't use regular expressions.

    Perl has the ability to automatically evaluate as a number or a string based on context. 01-09 will evaluate to 1-9 in the numeric context. So, you can simply check for a value:

    print "Enter in a month: ";
    chomp($pattern = <STDIN>);
    # We only want to print if the pattern matches
    print "Pattern matches\n" if ($pattern < 13 && $pattern > 0);
    
    0 讨论(0)
  • 2020-12-11 01:21

    here's one way

    while(1){
        print "Enter in a month: ";
        $pattern = <STDIN>;
        chomp($pattern);
        if ($pattern =~ /^(Q|q)$/ ){last;}
        if ($pattern =~ /^[0-9]$/ || $pattern =~ /^[0-9][12]$/ ) {
            print "Pattern matches\n";
        }else{
            print "try again\n";
        }
    }
    

    output

    $ perl perl.pl
    Enter in a month: 01
    Pattern matches
    Enter in a month: 000
    try again
    Enter in a month: 12
    Pattern matches
    Enter in a month: 00
    try again
    Enter in a month: 02
    Pattern matches
    Enter in a month: 13
    try again
    Enter in a month:
    
    0 讨论(0)
  • 2020-12-11 01:22

    You shouldn't use a regular expression to do numeric range validation. The regular expression you want is:

    /^(\d+)$/
    

    Then,

    if ($1 >= 1 && $1 <= 12) {
        # valid month
    }
    

    This is much easier to read than any regular expression to validate a numeric range.

    As an aside, Perl evaluates regular expressions by searching within the target for a matching expression. So:

    /(0[1-9]|1[012])/
    

    searches for a 0 followed by 1 to 9, or a 1 followed by 0, 1, or 2. This would match "202" for example, and many other numbers. On the other hand:

    /(0?[1-9]|1[012])/
    

    searches for an optional 0 1 to 9, or a 1 followed by 0, 1, or 2. So "13" matches here because it contains a 1, matching the first half of the regex. To make your regular expressions work as you expect,

    /^(0?[1-9]|1[012])$/
    

    The ^ and $ anchor the search to the start and end of the string, respectively.

    0 讨论(0)
提交回复
热议问题