I need to accept an mathematical expression (including one or more unknowns) from the user and substitute values in for the unknowns to get a result.
I could use eval() to do this, but it's far too risky unless there is a way to recognise "safe" expressions.
I'd rather not write my own parser if I can help it.
I searched for a ready-made parser but the only one I found ( https://www.ruby-toolbox.com/gems/expression_parser , which seems to be the same as the one discussed at http://lukaszwrobel.pl/blog/math-parser-part-4-tests) seems to be limited to the "four rules" +-*/. I need to include exponential, log and trig functions at the very least.
Any suggestions?
UPDATE: EXAMPLE
include Math
def exp(x)
Math.exp(x)
end
def cos(x)
Math.cos(x)
end
pi=Math::PI
t=2
string= '(3*exp(t/2)*cos(3*t-pi/2))'
puts eval(string)
UPDATE - a pre-parsing validation step
I think I will use this regex to check the string has the right kinds of tokens in it:
/((((cos\(|sin\()|(tan\(|acos\())|((asin\(|atan\()|(exp\(|log\())|ln\()(([+-\/*^\(\)A-Z]|\d)+))*([+-\/*^\(\)A-Z]|\d)+/
But I will still implement the parsing method during the actual evaluation.
Thanks for the help!