输入字符串是这样的:
LineA:50
LineB:120
LineA:12
LineB:53
我想与的结果来代替LineB值MultiplyCalculatorMethod(LineAValue)
,其中LineAValue
高于该线的值LineB
和MultiplyCalculatorMethod
是我的其他的,复杂的C#方法.
在半码中,我想做这样的事情:
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";
Run Code Online (Sandbox Code Playgroud)
我写了一个Regex.Match
匹配LineA: value\r\nLineB: value
并将这些值分组.但是当我使用时Regex.Replace
,我只能提供一个"静态"结果来组合匹配的组,但我不能在那里使用C#方法.
所以我的问题是如何Regex.Replace其中Result是C#方法的结果,其中输入是LineA值.
您可以像这样使用MatchEvaluator:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
尝试使用以下替换重载。
public static string Replace( string input, string pattern, MatchEvaluator evaluator);
Run Code Online (Sandbox Code Playgroud)
MatchEvaluator 可以访问 Match 内容,并且可以调用任何其他方法来返回替换字符串。