0

I am developping a calculator function in Visual Basic. I think there is no basic one in the default .NET libraries.

I use System.Data.DataTable.Compute() to calculate the normal Math expression. But I want my function to solve functions like Sinus() or Round() as well.

Currently I am using Regex for this. For example for functions with one argument I use

Dim expr As String = Regex.Replace(Term, "(?<func>[A-Za-z]*?)\((?<arg1>[0-9,.]*?)\)", AddressOf FunctionLibrary.Funcs1)

the Sinus() function would look like this: sin(Number).

But this only allows to write Doubles or Integers into the argument. I can not write inner functions or even another math expression between the parentheses.

If I would write more functions as an argument, Regex would detect the first ")" inside the function, which is the closing parenthese of the inner function, as the end of the outer function.

Is there any way to make Regex recognize that theres an inner function as well?

If anyone knows an Evaluate() function for Visual Basic which is in the default .NET libraries, this might help me as well

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
Jan B.
  • 9
  • 2

1 Answers1

1

Is there any way to make Regex recognize that theres an inner function as well?

No, there is not. Regular expressions, as the name implies, solve Regular grammars and simple mathematical expressions are Context-Free. Regular expressions do not have a stack to match arbitrary expressions. For example, distinguishing between (()) and ()() require at least one character of lookahead (or backtracking). Yes, PCRE-style regular expressions can let you create a fixed number of lookahead characters, but so far as I know you have to specify the number of characters, and anyway this is not going to solve your problem.

Evaluating arithmetic expressions require handling precedence, subexpressions, possibly variables and types. Regular expressions cannot do this, attempting to do it with regular expressions will lead you into a pit of failure.

Nor are they even necessary. Evaluating mathematical expressions is a solved problem and there are dozens of parsers and evaluators written, tested, and ready for you to drop into your application. You have not given us enough information to decide which one would be best for you, and anyway Stack Overflow is not a tool advocacy site. You could start by going through the list at Gary Beene's Equation Parser review.

Dour High Arch
  • 21,513
  • 29
  • 75
  • 90