简体   繁体   English

使用C#替换数学表达式中的变量

[英]Replace variables in a mathematical expression using c#

I have a mathematical expression like following format. 我有一个类似以下格式的数学表达式。

var exp = $(x)+$(y)-tan($(z));

using this I get x,y,z in an array 使用这个我得到数组中的x,y,z

var dArray = Regex.Split(str, @"[^a-z\.]+").Where(c => c != "." && c.Trim() != "").ToList();

But I am trying to remove '$()' from equation first and then want to replace x,y and z variables. 但是我想先从等式中删除'$()',然后再替换x,y和z变量。 For example 例如

first --> x+y-tan(z)
second --> 5+6-tan(7)

Any solution? 有什么办法吗?

Just use Math.net something like this 只需使用Math.net这样的东西

var expression = Infix.ParseOrThrow("x+y-tan(z)")
var symbols = new Dictionary<string,FloatingPoint>
   {{ "x", 5 }, { "y", 6 }, { "z", 7 },};
Evaluate.Evaluate(symbols, expression).RealValue;

To get rid of the $ sign, just do "$...".TrimStart('$') 要摆脱$符号,只需执行"$...".TrimStart('$')

How about the below regex replace code. 下面的正则表达式替换代码如何。 It uses a capture group to obtain the letter inside $() 它使用捕获组获取$()中的字母

string exp = "$(x)+$(y)-tan($(z))";
string pattern =  @"\$\((\D)\)";

Regex rgx = new Regex(pattern);
string newExp = rgx.Replace(exp, "$1");
newExp = newExp.Replace("x", "5").Replace("y", "6").Replace("z", "7");

A simple find \\$\\(([^()]*)\\) 一个简单的发现\\$\\(([^()]*)\\)
and replace $1 并替换$1

should remove the $() while preserving it's contents. 应该在保留其内容的同时删除$()

 \$\(
 ( [^()]* )                    # (1)
 \)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM