Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

regex

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.

like image 366
JohnFx Avatar asked Aug 10 '09 19:08

JohnFx


People also ask

Can I use regex in replace?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.

How do you use the Replace function in Blueprism?

The Replace() function in calculate stage is the simplest possible one. It's not a regex one! If the text is not always that standard, then you should rather use a regular expressions. To do that, you need to use an object, that will invoke a regex code.


1 Answers

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();
      }
   )
);
like image 121
Guffa Avatar answered Oct 19 '22 10:10

Guffa