正则表达式Match.Value返回整个值,而不是匹配的组 [英] Regex Match.Value returning entire value, not the matched groups

查看:402
本文介绍了正则表达式Match.Value返回整个值,而不是匹配的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试实现一个相对简单的任务,即使用正则表达式从花括号之间存在的字符串中捕获值.我编写的表达式在我测试过的许多在线工具上都可以正常工作,但是.NET并非如此.

I am currently trying to achieve the relatively simple task of capturing values from a string which exist between sets of curly braces using a regular expression. The expression I have written works fine on a number of online tools I have tested it on, however this is not the case in .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}".

I would expect to get 3 matches of "Value1", "Value2", "Value3". However .NET is also returning the brackets, i.e. "{Value1}", "{Value2}", "{Value3}".

任何有关如何实现这一目标的帮助都将非常有用.

Any help on how this can be achieved would be great.

推荐答案

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

You used capturing groups (...), so what you want is in the Groups[1]:

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

MatchCollection matches = regex.Matches(str);

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

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

Another way is to use zero-width assertions:

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

MatchCollection matches = regex.Matches(str);

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

这样,正则表达式将搜索在\w+之前和之后的\w+},但是这两个字符将不属于匹配项.

In this way the Regex will search for \w+ that is preceded and followed by the { and }, but these two characters won't be part of the match.

这篇关于正则表达式Match.Value返回整个值,而不是匹配的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆