首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用MaskedTextBox实现日期时间选择功能。使用RegEx完成验证

使用MaskedTextBox实现日期时间选择功能。使用RegEx完成验证
EN

Stack Overflow用户
提问于 2010-02-02 18:44:45
回答 1查看 2.3K关注 0票数 2

我正试图为我的应用程序创建一个自定义控件,它将使用maskedTextBox限制输入数据。

现在,我想在C#中实现这一点。

代码语言:javascript
复制
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变成这样

代码语言:javascript
复制
    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;

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

代码语言:javascript
复制
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输入的三个变量中日期的年份、月份和日期

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-02-02 20:36:43

Perl的$1$2$3等同于C#的m.Groups[1].Valuem.Groups[2].Value等等。

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

代码语言:javascript
复制
Match m = Regex.Match(ddmmyyyy);
if (m.Success) {
    string day = m.Groups[1];
    string month = m.Groups[2];
    string year = m.Groups[3];
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2186670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档