【问题标题】:Problem with backreferences in C#'s regexC# 正则表达式中的反向引用问题
【发布时间】:2011-06-05 13:17:01
【问题描述】:

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

<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] 是整个 lineCaptures[1] 超出范围。为什么?

【问题讨论】:

  • 作为记录,您的正则表达式中没有(或不需要)任何反向引用,反向引用看起来像 \1

标签: c# regex backreference


【解决方案1】:

使用组,而不是捕获。您的结果将在 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 2018-07-13
    • 1970-01-01
    相关资源
    最近更新 更多