如何在 C# 正则表达式中正确访问捕获组的值?

How to properly access the value of a capture group in C# regex?

我有以下代码:

using System;
using System.Text.RegularExpressions;

public class Test
{
   public static void Main()
   {
      var r = new Regex(@"_(\d+)$");
      string new_name = "asdf_1";

      new_name = r.Replace(new_name, match =>
      {
         Console.WriteLine(match.Value);
         return match.Value;
         //return (Convert.ToUInt32(match.Value) + 1).ToString();
      });

      //Console.WriteLine(new_name);
   }
}

我希望 match.Value1,但打印为 _1。我做错了什么?

您正在获得整个 Match 的价值 - 您只需要一个组(组 1),您可以通过 Groups property and the GroupCollection indexer:

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