【问题标题】:How to properly access the value of a capture group in C# regex? [duplicate]如何在 C# 正则表达式中正确访问捕获组的值? [复制]
【发布时间】:2015-03-04 08:11:29
【问题描述】:

我有以下代码:

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。我做错了什么?

【问题讨论】:

  • 从模式中删除_?
  • @Selman22 我不能,_ 是一个重要的分隔符,我需要检查它。关键是,_ 不在捕获组中,所以它不应该出现。我想让它按原样与_ 一起工作。
  • match.Value 是整个匹配项。使用 match.Groups[1].Value.

标签: c# regex


【解决方案1】:

您将获得整个 Match 的值 - 您只需要一个可以通过 Groups propertyGroupCollection indexer 访问的组(组 1):

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

【讨论】:

  • 我正在尝试与match.Captures 相同,但我不确定有什么区别。
  • @void.pointer:我相信Captures 的重点是当一个组有多个捕获时。
  • 显然是I'm not the only one who's confused。谢谢你的帮助!这很好用。
猜你喜欢
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 2019-10-05
  • 2014-08-04
  • 2020-12-26
  • 2016-10-09
  • 1970-01-01
相关资源
最近更新 更多