0

I want to do a regex replace in C# dot net, and I want to know how many replacements were made. What is the best way?

The best I can do now is to look at the before/after to see if anything changed

var a = "gooodbaaad";
var b = Regex.Replace(a,"[oa]","x");
if (a != b) Debug.Write("changed");

but this seems rather indirect and not accurate in all cases.

John Henckel
  • 10,274
  • 3
  • 79
  • 79

2 Answers2

5

Try something like the following. It transforms all sequences of 1 or more word characters to the literal text {word} and counts the replacements. So, the source text

The quick brown fox jumped over the lazy dog.

would be transformed to

{word} {word} {word} {word} {word} {word} {word} {word} {word}.

And at the end of the operation, the variable cnt has the value 9.

Regex pattern      = new Regex( @"\w+" ) ;
string source      = GetMeMySourceData() ;
int    cnt         = 0 ;
string transformed = pattern.Replace( source , m => {
    ++cnt ;
    return "{word}" ;
  });

The power of closures.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
3

try to use another overload of Regex.Replace with MatchEvaluator

using System;
using System.Text.RegularExpressions;           

public class Program
{
    public static void Main()
    {
        int count = 0;
        var b = Regex.Replace("gooodbaaad", "[oa]", m=> { count++; return "x"; });

        Console.WriteLine(b);
        Console.WriteLine(count);           
    }
}

demo

ASh
  • 34,632
  • 9
  • 60
  • 82
  • Thanks. It was not obvious to me from MSDN that I could use lambda in this context. Now I know! – John Henckel Jun 05 '15 at 17:56
  • @JohnHenckel, fine! `MatchEvaluator` is a delegate, so you can use a lambda expression – ASh Jun 05 '15 at 18:02
  • Technically your answer is not complete. You should have `return m.Result("x")` in case the string `"x"` contains `$1` or stuff like that. – John Henckel Jun 05 '15 at 18:31
  • @JohnHenckel, thank you for comment. i can't agree that it is not correct, since there are no captured groups here – ASh Jun 05 '15 at 18:41