Validating linear equations with regular expressions?
How can I validate linear equations with regular expressions or is there another way besides using regular expressions. I will use ^ to denote an exponent.
2x + 3 = 8 //This should validate fine
3x + 2y + 4z = 12 //This should validate fine
4x^2 + 2y = 22 //This should not validate because of the power.
4xy + 3y = 45 //This should not validate because of the product of two unknowns.
2/x + 4y = 22 //This should not validate becaus开发者_开发问答e of the unknown in the denominator
(3/4)x + 3y + 2z = 40 //This should validate fine.
I'd start by writing a definition of a valid linear equation using Backus-Naur notation, with things like:
<integer> := <digit> | <integer> <digit>
<constant> := <integer> | ...
<variable> := <letter>
<term> := <constant> | <variable> | <constant> <variable>
and so on.
There are many ways to turn that into a validator. Having some experience with it, I'd use yacc or bison to write a parser that would only generate a parse tree if the input was a valid linear equation.
You might find regular expressions are too limited to do what you need - I just don't use them enough to know.
The cases you've mentioned are easy:
fail if /[xyz]\s*\^/;
fail if /\/\s*[xyz]/;
fail if /([xyz]\s*){2,}/;
(this is Perl syntax, assuming $_
contains the expression, and fail
is whatever it is you do when you want to give up.)
Here you can replace xyz
with whatever is a valid expression for one variable.
But in general this will require actual parsing of the expression, which is a job for lex/yacc or something like that, not a regular expression.
For example if "xy" is a legitimate variable name, then of course this all crumbles.
精彩评论