How can I use a calculated value in a RegEx replace operation in C#?

c#, regex

Solution

Try using the version of `Regex.Replace` that calls a function to determine what the replacement text should be:

public string Replace(string, MatchEvaluator);

http://msdn.microsoft.com/en-us/library/aa332127(VS.71).aspx

The function could then look at the matched text (the `Match` object is supplied as the argument to the evaluator function) and return a string with the proper calculated value.

Problem

I'm looking for a way to use the length of a match group in the replace expression with the c# regex.replace function. That is, what can I replace ??? with in the following example to get the desired output shown below? Example: ``` val = Regex.Replace("xxx", @"(?<exes>x{1,6})", "${exes} - ???"); ``` Desired output ``` X - 3 ``` Note: This is an extremely contrived/simplified example to demonstrate the question. I realize for this example a regular expression is not the ideal way of doing this. Just trust me that the real world application of the answer is part of a more complex problem that does necessitate the use of a RegEx replace here.

Original source