Replace all occurrences of your known variables with a numeric constant. In your code, that would be x[0]
, x[1]
, and x[2]
. Note that in C lots of intermediate whitespace is allowed, even inside variables: x [ 1 ]
is valid. (Also: x[01]
is valid. x[0x01]
is valid. If the array is larger than 8 elements: x[010]
is valid and is actually x[8]
. 1[x]
is valid and is equal to x[1]
.)
The numerical constant must in itself be valid, and preferably not equal to 0
. (Just to prevent a parser stating 1/x[0]
is invalid!)
When replacing, insert a single space before and after your constant. This is to prevent a change of x[1]2
to 12
. Do not use parentheses! With those, sin x[1]
is invalid but its replacement, sin(1)
, is.
With this, an input string
x[0]*x[0] + x[1] + 1
is translated into
1 * 1 + 1 + 1
which can be validated with regular procedures; see for example Safe expression parser in Python; or, since you don't need to calculate but only validate, write your own.