0

I have a mathematical expression like following format.

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

using this I get x,y,z in an array

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. For example

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

Any solution?

3 Answers 3

3

Just use Math.net something like this

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('$')

Sign up to request clarification or add additional context in comments.

4 Comments

How to remove '$()'?
the () jsut leave it doesn't influence and the $ just string.Replace with an empty string
is there possible to add custom symbols like a1,a2 etc? When I tried to evaluate a1+ a2 using 'Infix.ParseOrThrow' it get error
No, sadly I think you can only have letters in the symbols
1

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");

Comments

0

A simple find \$\(([^()]*)\)
and replace $1

should remove the $() while preserving it's contents.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.