4

目标是从中提取时间和日期字符串:

<strong>Date</strong> - Thursday, June 2 2011 9:00PM<br>

这是代码:

Match m = Regex.Match(line, "<strong>Date</strong> - (.*) (.*)<br>");
date = m.Captures[0].Value;
time = m.Captures[1].Value;

由于正则表达式是贪婪的,它应该匹配第一组一直到最后一个空格。但事实并非如此。Captures[0]是整体line并且Captures[1]超出范围。为什么?

4

1 回答 1

4

使用组,而不是捕获。您的结果将在 Groups[1] 和 Groups[2] 中。

就个人而言,我建议命名这些组:

Match m = Regex.Match(line, "<strong>Date</strong> - (?<date>.*) (?<time>.*)<br>");
if( m.Success )
{
    date = m.Groups["date"].Value;
    time = m.Groups["time"].Value;
}
于 2011-06-05T13:26:56.420 回答