使用MaskedTextBox实现日期时间选择器功能。使用RegEx进行验证

时间:2010-02-02 18:44:46

标签: c# .net regex winforms perl

我正在尝试专门为我的应用程序创建一个自定义控件,该控件将使用maskedTextBox来限制输入的输入数据。

现在我想在C#中实现它。

class CustomDateMask:System.Windows.Forms.MaskedTextBox

this.Mask = "00/00/2\000"; // For year 2000 and above, date format is "dd/mm/yyyy"
this.ValidatingType = typeof(System.DateTime);

我看到了一个正则表达式,通过捕获输入离开和按键事件限制日期来验证我的日期。

现在我的RegExp就像这样

    string regYear  =@"(200[8,9]|201[0-9])";  //for year from 2008-2019  Plz correct this RegEx if wrong.
    string regMonth =@"(0[1-9]|1[012])";
    string regDate  =@"(0[1-9]|[12][0-9]|3[01])";
    string seperator=@"[- /]";

    string ddmmyyyy=regDate+seperator+regMonth+seperator+regYear;

我看到了一个关于正则表达式的 link 来检查日期格式。 现在我想在C#中使用此代码,我在上面提供了链接。此代码是用Perl编写的,我想在C#中执行相同的功能。但我不知道如何从这个正则表达式中检索日期,月份,年份,如下所示。从1美元,2美元,3美元。

sub isvaliddate {
  my $input = shift;
  if ($input =~ m!^((?:19|20)\d\d)[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$!) {
    # At this point, $1 holds the year, $2 the month and $3 the day of the date entered
    if ($3 == 31 and ($2 == 4 or $2 == 6 or $2 == 9 or $2 == 11)) {
      return 0; # 31st of a month with 30 days
    } elsif ($3 >= 30 and $2 == 2) {
      return 0; # February 30th or 31st
    } elsif ($2 == 2 and $3 == 29 and not ($1 % 4 == 0 and ($1 % 100 != 0 or $1 % 400 == 0))) {
      return 0; # February 29th outside a leap year
    } else {
      return 1; # Valid date
    }
  } else {
    return 0; # Not a date
  }
}

我想使用this.DateOnly,this.MonthOnly,this.YearOnly返回用户日期部分,月份部分和年份部分,我需要提取这些值。

我的主要关注

保存从maskedTextBox

输入三个变量的日期的年,月和日

1 个答案:

答案 0 :(得分:3)

Perl的$1$2$3等同于C#的m.Groups[1].Valuem.Groups[2].Value,依此类推。

要在示例中提取它们,您可以使用

Match m = Regex.Match(ddmmyyyy);
if (m.Success) {
    string day = m.Groups[1];
    string month = m.Groups[2];
    string year = m.Groups[3];
}