10

In AS3 you have a function on a string with this signature:

function replace(pattern:*, repl:Object):String 

The repl:Object can also specify a function. If you specify a function, the string returned by the function is inserted in place of the matching content.

Also, is it possible to get the the original string in which I want to replace things?

(In AS3 you can get the original string by

var input:String = arguments[2]; //in the callback function

)

I don't see a property in the Match class containing the original string...

Jeff Atwood
  • 63,320
  • 48
  • 150
  • 153
Lieven Cardoen
  • 25,140
  • 52
  • 153
  • 244

3 Answers3

13
static void Main() {

    string s1 = Regex.Replace("abcdefghik", "e",
        match => "*I'm a callback*");

    string s2 = Regex.Replace("abcdefghik", "c", Callback);
}
static string Callback(Match match) {
    return "*and so am i*";
}

Note you have access to the matched data via the argument (and match.Value in particular, unless you want access to the regex groups (.Groups) etc).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Is it possible to get the the original string in which I want to replace things? (In AS3 you can get the original string by var input:String = arguments[2]; //in the callback function ) I don't see a property in the Mach class containing the original string... – Lieven Cardoen Jan 14 '09 at 09:10
6

In order to do this in C#, use System.Text.RegularExpressions.Regex.Replace() which takes a callback.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
5

Just as an example to make the existing answers absolutely concrete, and showing how lambda expressions can be handy:

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        var template = "On $today$ you need to do something.";
        var regex = new Regex(@"\$today\$");
        var text = regex.Replace(template,
            match => DateTime.Now.ToString("d"));
        Console.WriteLine(text);
    }
}

(Marc's answer appeared while I was writing this, but I'll leave it up as a complete example unless anyone thinks it's just redundant. I'm happy to delete it if suggested.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194