【问题标题】:Regex and date matching正则表达式和日期匹配
【发布时间】:2010-07-30 12:44:10
【问题描述】:

我想使用正则表达式搜索字符串中所有可能的日期。 在我的代码中,我有这个:

String dateSearchPattern = @"(?<Day>\d{2}).(?<Month>\d{2}).(?<Year>\d{4})|(?<Day>\d{2}).(?<Month>\d{2}).(?<Year>\d{2})";

// date format: dd.mm.yyyy or d.m.yyyy or dd.mm.yy or d.m.yy
String searchText = "20.03.2010.25.03.10";

Regex.Matches(searchText, dateSearchPattern); // the matching SHOULD give a count of 2

上面的代码只给出了 1 个匹配项,而它应该给出 2 个匹配项。当日期格式为 d.m.yyyy 或 d.m.yy 时,我还需要一个模式。

【问题讨论】:

  • 请同时提供样本数据。 :-)

标签: c# regex


【解决方案1】:

图案看起来完全没问题。它给了两个匹配。您是否有任何机会使用以下行来检查计数?

var match = Regex.Matches(searchText, dateSearchPattern);
Console.WriteLine(match.Count);

我在 .Net 3.5 (w/o sp1) 上使用了 SD 3,您的代码给出了您想要的结果。

【讨论】:

    【解决方案2】:

    您可以将模式更改为:

    "(?<Day>\d{1,2}).(?<Month>\d{1,2}).(?:(?<Year>\d{4})|(?<Year>\d{2}))"
    

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 1970-01-01
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      相关资源
      最近更新 更多