-4
我有以下字符串:插入在正则表达式
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);
请协助
我有以下字符串:插入在正则表达式
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);
请协助
我会用Regex.Replace,然后使用自定义MatchEvaluator转换你的价值观和插入这些检查: http://msdn.microsoft.com/en-us/library/cft8645c(v=vs.110).aspx
这看起来是这样的:没有任何答案标记
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);
}
}
4个问题,如果有人努力回答你的问题,你需要标记答案 – 2012-08-08 07:47:24