C# 正则表达式中的反向引用问题
目标是从中提取时间和日期字符串:
<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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用组,而不是捕获。您的结果将显示在组[1] 和组[2] 中。
就我个人而言,我建议为这些组命名:
Use Groups, not Captures. Your results will be in Groups[1] and Groups[2].
And personally, I'd recommend naming the groups: