C# 在正则表达式中插入
我有以下字符串:C# 在正则表达式中插入,c#,regex,C#,Regex,我有以下字符串: 10-5*tan(40)-cos(0)-40*sin(90); 我提取了数学函数并计算了它们的值: tan(40) = 1.42; cos(0) = 1; sin(90) = 0; 我想将这些值插入到表达式字符串中,如下所示: 10-5*(1.42)-(1)-40*(0); 请协助我将使用正则表达式。替换,然后使用自定义MatchEvaluator转换您的值并插入这些值,请检查: 这看起来像: class Program { static string Conv
10-5*tan(40)-cos(0)-40*sin(90);
我提取了数学函数并计算了它们的值:
tan(40) = 1.42;
cos(0) = 1;
sin(90) = 0;
我想将这些值插入到表达式字符串中,如下所示:
10-5*(1.42)-(1)-40*(0);
请协助我将使用正则表达式。替换,然后使用自定义MatchEvaluator转换您的值并插入这些值,请检查: 这看起来像:
class Program
{
static string ConvertMathFunc(Match m)
{
Console.WriteLine(m.Groups["mathfunc"]);
Console.WriteLine(m.Groups["argument"]);
double arg;
if (!double.TryParse(m.Groups["argument"].Value, out arg))
throw new Exception(String.Format("Math function argument could not be parsed to double", m.Groups["argument"].Value));
switch (m.Groups["mathfunc"].Value)
{
case "tan": return Math.Tan(arg).ToString();
case "cos": return Math.Cos(arg).ToString();
case "sin": return Math.Sin(arg).ToString();
default:
throw new Exception(String.Format("Unknown math function '{0}'", m.Groups["mathfunc"].Value));
}
}
static void Main(string[] args)
{
string input = "10 - 5 * tan(40) - cos(0) - 40 * sin(90);";
Regex pattern = new Regex(@"(?<mathfunc>(tan|cos|sin))\((?<argument>[0-9]+)\)");
string output = pattern.Replace(input, new MatchEvaluator(Program.ConvertMathFunc));
Console.WriteLine(output);
}
}
类程序
{
静态字符串ConvertMathFunc(匹配m)
{
Console.WriteLine(m.Groups[“mathfunc”]);
Console.WriteLine(m.Groups[“argument”]);
双精氨酸;
if(!double.TryParse(m.Groups[“argument”].Value,out arg))
抛出新异常(String.Format(“无法将数学函数参数解析为double”,m.Groups[“argument”].Value));
开关(m.Groups[“mathfunc”].值)
{
案例“tan”:返回Math.tan(arg.ToString();
case“cos”:返回Math.cos(arg.ToString();
案例“sin”:返回Math.sin(arg.ToString();
违约:
抛出新异常(String.Format(“未知的数学函数“{0}”,m.Groups[“mathfunc”].Value));
}
}
静态void Main(字符串[]参数)
{
字符串输入=“10-5*tan(40)-cos(0)-40*sin(90);”;
正则表达式模式=新正则表达式(@“(?(tan|cos|sin))\((?[0-9]+)\)”;
字符串输出=pattern.Replace(输入,新的MatchEvaluator(Program.ConvertMathFunc));
控制台写入线(输出);
}
}
4个没有标记任何答案的问题,如果有人试图回答您的问题,您需要标记答案