How to use computed value in RegEx replacement operation in C #?

I am looking for a way to use the length of a match group in a replace expression using the C # regex.replace function.

That is, what can I replace ??? in the following example to get the desired result shown below?

Example:

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

Desired Conclusion

 X - 3 

Note: This is an extremely contrived / simplified example to demonstrate the question. I understand that for this example, regex is not an ideal way to do this. Just trust me that the real response application is part of a more complex problem that requires using RegEx here.

+7
c # regex
source share
3 answers

Try using the version of Regex.Replace that calls the 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

Then the function could view the matched text (the Match object is supplied as an argument to the evaluator function) and returns a string with the corresponding calculated value.

+8
source share

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(); } ) ); 
+13
source share

Try

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

with MatchEvaluator example below

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

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

+3
source share

All Articles