public class ExpressionTree extends Object
Expression string parser. The parser returns an Expression object which can be evaluated.
The elements of an expression fall into two categories, operators and terms. Terms include variables, functions and values. Although values do not subclass TermNode, they are processed in a similar way during the parsing.
The operators are exponent (^), times (*), divide (/), plus (+) and minus (-). The exponent has the highest precedence, then times and divide (which have an equal level of precedence) and then plus and minus (which have an equal level of precedence). For those operators that have an equal level of precedence, the operator that comes first (reading from left to right) gets the higher level of precedence. For example, a-b+c becomes ((a-b)+c)
During the parsing, the string is scanned from left to right. Either a term or an operator will come next. If it is a term, then it may be preceded by an optional + or - sign. For example, For example +a/-b/+c is valid, and becomes ((a/(-b))/c). If a term is not explicitly signed, then by default it is positive.
If the first character of a term is a decimal (.) or a digit (0-9) then the term marks the beginning of a value. The first character that is found that is not a digit or a decimal marks the end of the value, except if the character is an 'e' or an 'E'. In this case, the first digit immediately following can be a plus sign, minus sign or digit. E.g. 1.23E+4. At this point, the first character that is not a digit marks the end of the value.
If the first character of a term is not a decimal, digit, open bracket '(', a close bracket ')', a comma ',', a whitespace character ' ', '\t', '\n', or an operator, then the character marks the beginning of a variable or function name. The first character found that is an operator, whitespace, open bracket, close bracket or comma marks the end of the name. If the first non-whitespace character after a name is an open bracket, then it marks the beginning of the function parameters, otherwise the term is marked as a variable.
Functions that accept more than one parameter will have the parameters separated by commas. E.g. f(x,y). Since the parameters of a function are also expressions, when a comma is detected that has exactly one unbalanced open bracket to the left, a recursive call is made passing in the substring. E.g. f(g(x,y),z), a recursive call will occur passing in the substring "g(x,y)".
Miscellaneous Notes
Expression
Modifier and Type | Method and Description |
---|---|
static Expression |
parse(String s)
Returns an expression-tree that represents the expression string.
|
public static Expression parse(String s)
ExpressionParseException
- If the string is invalid.Copyright © 2016. All rights reserved.