How to replace a Regex match group item with a method result

The input line looks something like this:

LineA: 50

LineB: 120

LineA: 12

LineB: 53

I would like to replace the LineB values ​​with the result of MultiplyCalculatorMethod(LineAValue) , where LineAValue is the value of the line above LineB and MultiplyCalculatorMethod is my other, complex C # method.

In semi-code, I would like to do something like this:

 int MultiplyCalculatorMethod(int value) { return 2 * Math.Max(3,value); } string ReplaceValues(string Input) { Matches mat = Regex.Match(LineA:input_value\r\nLineB:output_value) foreach (Match m in mat) { m.output_value = MultiplyCalculatorMethod(m.input_value) } return m.OutputText; } Example: string Text = "LineA:5\r\nLineB:2\r\nLineA:2\r\nLineB:7"; string Result = ReplaceValues(Text); //Result = "LineA:5\r\nLineB:10\r\nLineA:2\r\nLineB:6"; 

I wrote a Regex.Match to match LineA: value\r\nLineB: value and get these values ​​in groups. But when I use Regex.Replace , I can only provide a β€œstatic” result that combines groups from a match, but I cannot use C # methods there.

So my questions are how is Regex.Replace where Result is the result of the C # method, where input is the value of LineA.

+7
c # regex
source share
2 answers

Try using the following reboot.

 public static string Replace( string input, string pattern, MatchEvaluator evaluator); 

MatchEvaluator has access to the contents of the match and can call any other methods to return the replacement string.

+4
source share

You can use MatchEvaluator as follows:

 public static class Program { public static void Main() { string input = "LineA:5\r\nLineB:2\r\nLineA:2\r\nLineB:7"; string output = Regex.Replace(input, @"LineA:(?<input_value>\d+)\r\nLineB:\d+", new MatchEvaluator(MatchEvaluator)); Console.WriteLine(output); } private static string MatchEvaluator(Match m) { int inputValue = Convert.ToInt32(m.Groups["input_value"].Value); int outputValue = MultiplyCalculatorMethod(inputValue); return string.Format("LineA:{0}\r\nLineB:{1}", inputValue, outputValue); } static int MultiplyCalculatorMethod(int value) { return 2 * Math.Max(3, value); } } 
+7
source share

All Articles