正则表达式 Match.Value 返回整个值,而不是匹配的组
Posted
技术标签:
【中文标题】正则表达式 Match.Value 返回整个值,而不是匹配的组【英文标题】:Regex Match.Value returning entire value, not the matched groups 【发布时间】:2015-05-06 17:03:19 【问题描述】:我目前正在尝试实现相对简单的任务,即使用正则表达式从存在于花括号集之间的字符串中捕获值。我编写的表达式在我测试过的许多在线工具上运行良好,但在 .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”。
任何关于如何实现这一点的帮助都会很棒。
【问题讨论】:
【参考方案1】:你使用了捕获组(...)
,所以你想要的是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);
这样,Regex 将搜索 \w+
之前和之后是 和
,但这两个字符不会成为匹配的一部分。
【讨论】:
【参考方案2】:您可以使用环视:
Regex regex = new Regex( @"(?<=\)(\w+)(?=\)");
或使用匹配组#1。
【讨论】:
【参考方案3】:你可以使用
Console.WriteLine(match.Groups[1].Value);
来自MSDN:
如果正则表达式引擎可以找到匹配项,则第一个元素 由返回的 GroupCollection 对象(索引 0 处的元素)的 Groups 属性包含一个匹配整个正则的字符串 表达模式。每个后续元素,从索引 1 向上, 表示捕获的组,如果正则表达式包括 捕获组。
所以match.Groups[0].Value
本身就是Value1
而match.Groups[1].Value
就是Value1
。
【讨论】:
以上是关于正则表达式 Match.Value 返回整个值,而不是匹配的组的主要内容,如果未能解决你的问题,请参考以下文章