从字符串中提取日期值

问题描述 投票:0回答:2

论坛。

我的代码从Excel文件读取和获取变量“textContainingDate”下面的字符串:

"Employee Filter: All Employees; Time Entry Dates: 01/07/2016-01/07/2016; Exceptions: All Exceptions"

我希望做的是提取字符串中的日期值。虽然有被解读为日期范围两个日期,这两个日期将永远是相同的。我的想法是,无论是场景,我会得到满意的第一次约会我碰到过。

var dateTime = DateTime.ParseExact(textContainingDate, "MM/dd/yyyy", CultureInfo.CurrentCulture);

我试着用上面的说法,这是我从其他计算器问题,并在谷歌搜索的文章拼凑起来的。从我读过,我相信,因为它是唯一的期望日期字符串失败。

任何对朝读什么书全文,并找到解决方案的解决方案和/或方向建议表示赞赏。

c# date parsing string-parsing
2个回答
3
投票

您可以使用Regex.Match让你满足第一个日期字符串。此方法返回在输入串中的正则表达式模式匹配的第一个串。

string stringWithDate = "Employee Filter: All Employees; Time Entry Dates: 01/07/2016-01/07/2016; Exceptions: All Exceptions";
Match match = Regex.Match(stringWithDate, @"\d{2}\/\d{2}\/\d{4}");
string date = match.Value;
if (!string.IsNullOrEmpty(date)) {
    var dateTime = DateTime.ParseExact(date, "MM/dd/yyyy", CultureInfo.CurrentCulture);
    Console.WriteLine(dateTime.ToString());
}

什么是正则表达式\d{2}\/\d{2}\/\d{4}的作用: enter image description here


0
投票
 var regex = new Regex(@"\d{2}\/\d{2}\/\d{4}");
 foreach (Match m in regex.Matches(line))
 {
  DateTime dt;
  if (DateTime.TryParseExact(m.Value, "MM/dd/yyyy", null, DateTimeStyles.None, out dt))
  remittanceDateArr[chequeNo - 1] = dt.ToString("MM/dd/yyyy");                                   
  rtbExtract.Text = rtbExtract.Text + remittanceDateArr[chequeNo - 1] + "\n";
  }
© www.soinside.com 2019 - 2024. All rights reserved.