C # Replace callback function as in AS3

In AS3, you have a function in a line with this signature:

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

Answer: An object can also specify a function. If you specify a function, the string returned by the function will be inserted instead of the corresponding content.

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

(In AS3 you can get the source string

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

)

I do not see the properties in the Match class containing the source string ...

+6
function c # regex replace actionscript-3
source share
3 answers

To do this in C #, use System.Text.RegularExpressions.Regex.Replace() , which accepts the callback.

+6
source share
 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*"; } 

Please note: you have access to the matched data using an argument (and match.Value in particular if you do not want access to regular expression groups ( .Groups ), etc.).

+12
source share

As an example, to make existing answers absolutely concrete and show how lambda expressions can be used:

 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 came when I wrote this, but I’ll leave it as a complete example if someone doesn’t think that it’s just superfluous. I am glad to remove it, if prompted.)

+5
source share

All Articles