tags:

views:

592

answers:

2

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.

+2  A: 

Try using following Replace overload.

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

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

Dmitry Ornatsky
+2  A: 

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); 
    }
}
Martin Brown