C# 正则表达式中的反向引用问题

发布于 2024-11-14 00:31:24 字数 434 浏览 3 评论 0原文

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

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

The goal is to extract time and date strings from this:

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

Here's the code:

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

Thanks to the regex being greedy, it should match the first group all the way up to the last space. But it doesn't. Captures[0] is the whole line and Captures[1] is out of range. Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

破晓 2024-11-21 00:31:24

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

Use Groups, not Captures. Your results will be in Groups[1] and Groups[2].

And personally, I'd recommend naming the groups:

Match m = Regex.Match(line, "<strong>Date</strong> - (?<date>.*) (?<time>.*)<br>");
if( m.Success )
{
    date = m.Groups["date"].Value;
    time = m.Groups["time"].Value;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文