.

RegEx.Replace multiple tokens c#

This is just  a quick tutorial of how to use RegEx.Replace to replace multiple tokens in C#.

Example of what we want to accomplish:

Transform some text e.g. “{exec:DoThis:param=32}” into “DoThis(32)” using regular expressions

public void RegEx-Replace-using-tokens()
{
    string input = "{exec:DoThis:param=32}";
    var output_txt = Regex.Replace(input, 
         "{exec:(?<p1>\\S+):param=(?<p2>\\d+)}", "$1($2)");
}

output_txt will be: “DoThis(32)”

p1 and p2 could have been named anything (as long as they are different – ie not both “p1″)

The token $1 is basically grabbed from the ………… below:
?(<my_parameter_name_exposed_as_$1> ……….. )                     this will result in $1  =  ……………
and the value can also be accessed as follow:
string functionName = matches[i].Groups["my_parameter_name_exposed_as_$1"].Value;

so e.g.    ?(<anthing>Hi)  will result in $1 to be “Hi”

So if you e.g. want to grab the “ell” in Hello as $1, you can use the following regular expression:

“H(?<param>ell)o”

 

 

What's your thoughts on this?

*

Protected by WP Anti Spam