i want evaluate at runtime some string expression like:
((foo = true) or (bar <> 'test')) and (baz >= 1)
The string are inputted by user. The user can create a rule by coupling a property choised from a set (eg. foo
, bar
, baz
), inputting the target value to evaluate (string
, number
and boolean
) and choising the operator (=
, <>
, >
, <
), eg.:
| Id | Property | Operator | Value | Expression |
-------------------------------------------------------------------------------------------
| $1 | foo | = | true | (foo = true) |
-------------------------------------------------------------------------------------------
| $2 | bar | <> | 'test' | (bar <> 'test') |
-------------------------------------------------------------------------------------------
| $3 | baz | >= | 1 | (baz >= 1) |
-------------------------------------------------------------------------------------------
the single rule can be coupled and nested in child/parent rule by choosing an operator like and
, or
, eg.:
| Id | Property | Operator | Value | Expression |
-------------------------------------------------------------------------------------------
| $1 | foo | = | true | (foo = true) |
-------------------------------------------------------------------------------------------
| $2 | bar | <> | 'test' | (bar <> 'test') |
-------------------------------------------------------------------------------------------
| $3 | baz | >= | 1 | (baz >= 1) |
-------------------------------------------------------------------------------------------
| $4 | $1 | or | $2 | ((foo = true) or (bar <> 'test')) |
-------------------------------------------------------------------------------------------
| $5 | $4 | and | $3 | ((foo = true) or (bar <> 'test')) and (baz >= 1) |
-------------------------------------------------------------------------------------------
in peseudo code, the idea is:
aExpressionEngine := TExpressionEngine.Create;
try
// Adds to the evaluation scope all the properties with the
// inputted value. AddToScope accept string, variant
aExpressionEngine.AddToScope('foo', false);
aExpressionEngine.AddToScope('bar', 'qux');
aExpressionEngine.AddToScope('baz', 10);
// evaluate the expression, the result is always a boolean
Result := aExpressionEngine.eval('(((foo = true) or (bar <> ''test'')) and (baz >= 1))');
finally
aExpressionEngine.free;
end;
in this pseudo code example, the expression to evaluate become (after replacing the properties with the scope value):
(((false = true) or ('qux' <> 'test')) and (10 >= 1)) // TRUE
by googling, i have found a bit of library for evaluate math expression, but nothing for logical condition evaluating.
Has delphi something for evaluate string expression?