【问题标题】:Implement Date Time Picker functionality with MaskedTextBox. Validation done with RegEx使用 MaskedTextBox 实现日期时间选择器功能。使用 RegEx 完成验证
【发布时间】:2010-02-02 18:44:45
【问题描述】:

我正在尝试专门为我的应用程序创建一个自定义控件,该控件将使用 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);

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

现在我的正则表达式变成了这样

    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、$2、$3 等是正则表达式捕获的值,按位置命名。
  • @Anonymous:那么我应该如何在 C# 中捕获相同的内容,位置没有问题,请参阅我的正则表达式 ddmmyyyy 在这种情况下如何捕获这些值

标签: c# .net regex winforms perl


【解决方案1】:

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];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    相关资源
    最近更新 更多