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

前端 未结 9 821
孤街浪徒
孤街浪徒 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:00

    "^(1[012]|0?[1-9])$" would be better because regular expression is assessed first one first. Let's say you want to match '12' and you write "^(0?[1-9]|1[012])$", then '1' will be picked because 0?[1-9] is taken first.

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

    If you really like to use regex, you need to put ^ and $, like

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

    it will not match 13, 14 ....

    0 讨论(0)
  • 2020-12-11 01:04
    [^d>12|d<0] OR ^[d>12|d<0]
    
    0 讨论(0)
  • 2020-12-11 01:05

    To give you hint - month number "120" also matches in your version :-)

    Change:

    my $month = "(0[1-9]|1[012])";
    

    to

    my $month = /^(0[1-9]|1[012])$/;
    

    and then play more with it

    0 讨论(0)
  • 2020-12-11 01:05

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

    the parens are so you can use this inside another block, for example if matching for an entire yyyy-MM-dd date format

    source: http://www.regular-expressions.info/dates.html

    0 讨论(0)
  • 2020-12-11 01:12

    To test month / year :

    ^(0?[1-9]|1[012])\/([2-9][0-9)]{3})$
    
    0 讨论(0)
提交回复
热议问题