我目前正在尝试完成一项相对简单的任务,即使用正则表达式从存在于大括号组之间的字符串中捕获值。我编写的表达式在我测试过的许多在线工具上运行良好,但在 .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);
}
我希望得到“Value1”、“Value2”、“Value3”的 3 个匹配项。然而,.NET 也返回括号,即“{Value1}”、“{Value2}”、“{Value3}”。
任何有关如何实现这一目标的帮助都会很棒。
最佳答案
您使用了捕获组 (...)
,所以您想要的是在 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+
,但是这两个字符赢了'成为比赛的一部分。
关于c# - Regex Match.Value 返回整个值,而不是匹配的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28875959/