【问题标题】:Regex Match.Value returning entire value, not the matched groups正则表达式 Match.Value 返回整个值,而不是匹配的组
【发布时间】: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}”。

任何关于如何实现这一点的帮助都会很棒。

【问题讨论】:

    标签: c# regex curly-brackets


    【解决方案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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-02
          • 2022-01-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多