0

I have the following code:

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);
   }
}

I expect match.Value to be 1, but it is printing as _1. What am I doing wrong?

void.pointer
  • 24,859
  • 31
  • 132
  • 243

1 Answers1

5

You're getting the value of the whole Match - you only want a single group (group 1) which you can access via the Groups property and the GroupCollection indexer:

Console.WriteLine(match.Groups[1]);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I was trying the same with `match.Captures`, I am not sure of the difference. – void.pointer Jan 06 '15 at 16:06
  • @void.pointer: I believe the point of `Captures` is when a single group has multiple captures. – Jon Skeet Jan 06 '15 at 16:09
  • Apparently [I'm not the only one who's confused](http://stackoverflow.com/questions/3320823/whats-the-difference-between-groups-and-captures-in-net-regular-expression). Thanks for your help! This works great. – void.pointer Jan 06 '15 at 16:10