如何使用正则表达式来验证月份输入? [英] How can I use a regular expression to validate month input?

查看:59
本文介绍了如何使用正则表达式来验证月份输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设置这个示例 Perl 片段来验证日期中的几个月:

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

我想接受的一些场景是:

Some scenarios I want to accept are:

MM米

#!/usr/bin/perl
use strict;
use warnings;

my $pattern;
my $month = "(0[1-9]|1[012])";
my $day = "(0[1-9]|[12]\d|3[01])";

system("cls");

do {

    print "Enter in a month: ";
    chomp($pattern = <STDIN>);

    # We only want to print if the pattern matches
    print "Pattern matches\n" if ($pattern =~ /$month/);


} while ($pattern ne "Q");

当我运行它时,它从 01-12 正确过滤,但是当我将正则表达式更改为:

When I run this, it correctly filters from 01-12 but when I change the regex to:

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

那么正则表达式允许 13、14 等......是什么?

then the regex allows 13, 14, etc... what gives?

推荐答案

如果你真的喜欢使用正则表达式,你需要把^和$,像

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

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

它不会匹配 13、14 ....

it will not match 13, 14 ....

这篇关于如何使用正则表达式来验证月份输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆