【问题标题】:Why am I not getting all my regex captures?为什么我没有得到我所有的正则表达式捕获?
【发布时间】:2014-04-30 17:35:53
【问题描述】:

我正在使用 .NET 的 Regex 从字符串中捕获信息。我有一个包含在条形字符中的数字模式,我想挑选出这些数字。这是我的代码:

string testStr = "|12||13||14|";
var testMatch = Regex.Match(testStr, @"^(?:\|([0-9]+)\|)+$");

但是,testMatch.Captures 只有 1 个条目,等于整个字符串。为什么它没有 3 个条目,121314?我错过了什么?

【问题讨论】:

  • 嗯。我原以为它已经捕获了14。无论如何,一个被捕获的群体通常会捕获一件事;无论如何,您可以将Matches(?<=\|)[0-9]+(?=\|) 一起使用。或者只是匹配[0-9]+。或者将|StringSplitOptions.RemoveEmptyEntries 分开(对吗?)。

标签: c# .net regex


【解决方案1】:

您想在Group 本身上使用Captures 属性——在本例中为testMatch.Groups[1]。这是必需的,因为正则表达式中可能有多个捕获组,并且它无法知道您指的是哪一个。

使用testMatch.Captures 可以有效地得到testMatch.Groups[0].Captures

This works 我:

string testStr = "|12||13||14|";
var testMatch = Regex.Match(testStr, @"^(?:\|([0-9]+)\|)+$");

int captureCtr = 0;
foreach (Capture capture in testMatch.Groups[1].Captures) 
{
    Console.WriteLine("Capture {0}: {1}", captureCtr++, capture.Value);
}

参考:Group.Captures

【讨论】:

  • 这个。这有点不直观,但我需要看看.Groups[1].Captures[1/2/3...]
  • @Jez 我澄清了我的回答。
猜你喜欢
  • 2021-11-23
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多