Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Regex replace match group item with method result

Tags:

c#

regex

The input string is something like this:

LineA: 50

LineB: 120

LineA: 12

LineB: 53

I would like to replace the LineB values with a result of MultiplyCalculatorMethod(LineAValue), where LineAValue is the value of the line above LineB and MultiplyCalculatorMethod is my other, complicated 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 is combining groups from the match, but I can not use C# methods there.

So my questions is how to Regex.Replace where Result is a result of C# method where input is LineA value.

like image 437
Tom Smykowski Avatar asked Apr 20 '09 11:04

Tom Smykowski


People also ask

Can I use regex in replace?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What does .*)$ Mean?

*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string.


1 Answers

You can use a MatchEvaluator like this:

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); 
    }
}
like image 83
Martin Brown Avatar answered Nov 10 '22 14:11

Martin Brown