tags:

views:

102

answers:

3

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.

+3  A: 

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.

Amber
Thanks. I was thinking I needed to do that, but before I went down that road, I just wanted to see if there was a keyword recognized by replace to make this operation simpler. Still, you've got my upvote and if no one responds with a shorthand way to accomplish this I'll accept this answer.
JohnFx
+2  A: 

Try

val = Regex.Replace("xxx", @"(?<exes>x{1,6})", new MatchEvaluator(ComputeReplacement));

with the MatchEvaluator example below

public String ComputeReplacement(Match matchResult) {
  return matchResult.Value.Length.ToString();
}

(partially stolen from the Regular Expressions Cookbook -- my bible haha)

NickAldwin
of course this is a very simple example
NickAldwin
+2  A: 

If you are using C# 3 you can simply create a MatchEvaluator from a lambda expression:

string val = Regex.Replace(
   "xxx",
   @"(?<exes>x{1,6})",
   new MatchEvaluator(
      m => m.Groups["exes"].Value[0] + " - " + m.Groups["exes"].Value.Length.ToString()
   )
);

In C# 2 you can use a delegate:

string val = Regex.Replace(
   "xxx",
   @"(?<exes>x{1,6})",
   new MatchEvaluator(
      delegate(Match m) {
         return m.Groups["exes"].Value[0] + " - " + m.Groups["exes"].Value.Length.ToString();
      }
   )
);
Guffa