Regex Match.Value返回整个值,而不是匹配的组

时间:2015-03-05 10:45:32

标签: c# regex curly-brackets

我目前正在尝试使用正则表达式从字符串中捕获值,这些字符串存在于花括号的集合之间。我编写的表达式在我测试过的许多在线工具上运行良好,但在.NET中并非如此。

String str= "{Value1}-{Value2}.{Value3}";
Regex regex = new Regex( @"\{(\w+)\}");

MatchCollection matches = regex.Matches(str);

foreach(Match match in matches)
{
    Console.WriteLine(match.Value);
}

我希望能获得3场比赛的" Value1"," Value2"," Value3"。但是,.NET也会返回括号,即" {Value1}"," {Value2}"," {Value3}"。

任何有关如何实现这一目标的帮助都会很棒。

3 个答案:

答案 0 :(得分:4)

您使用了捕获群组(...),因此您想要的是Groups[1]

Regex regex = new Regex(@"\{(\w+)\}");

MatchCollection matches = regex.Matches(str);

foreach (Match match in matches) {
    Console.WriteLine(match.Groups[1].Value);
} 

另一种方法是使用零宽度断言:

Regex regex = new Regex(@"(?<=\{)(\w+)(?=\})");

MatchCollection matches = regex.Matches(str);

foreach (Match match in matches) {
    Console.WriteLine(match.Value);
} 

通过这种方式,正则表达式将搜索\w+{之前和之后的},但这两个字符不会成为匹配的一部分。

答案 1 :(得分:2)

您可以使用外观:

Regex regex = new Regex( @"(?<=\{)(\w+)(?=\})");

或使用匹配的组#1。

答案 2 :(得分:0)

您可以使用

Console.WriteLine(match.Groups[1].Value);

来自MSDN

  

如果正则表达式引擎可以找到匹配的第一个元素   由...返回的GroupCollection对象(索引0处的元素)   Groups属性包含与整个常规字符串匹配的字符串   表达模式。每个后续元素,从索引一向上,   表示正则表达式包含的捕获组   捕获组。

因此match.Groups[0].Value本身为{Value1}match.Groups[1].ValueValue1