Home
Categories
Dictionnary
Download
Project Details
Changes Log

Parsing an expression


    1  Using global variables
    2  Configuring the parser
       2.1  Accepting undefined global variables
    3  Notes

To parse an expression, you need to use one of the parsexxx static methods of the ExpressionJ class[1] . The methods return an Equation which can evaluated.

Expressions can be parsed from a String, an URL, or a File.

Using global variables

Main Article: creating global variables

A list of global variables can be passed−on for the parsing, which allows to set variable values, and even share these values among several expressions. For example:

      List<Variable> vars = new ArrayList();  
      Variable var = new Variable("a", Expression.TYPE_INTEGER);  
      vars.add(var);  
      Equation equation = ExpressionJ.parse("return a + 1;", vars);  
        
      var.setValue(2);  
      Object result = equation.eval();   
      // the result is 3           

Configuring the parser

Accepting undefined global variables

By default if a global variable is defined in the expression but not in the list of defined global variables passed on for the parsing, this variable will be created. For example:

      Equation equation = ExpressionJ.parse("a = 2; return a + 1;");  

Then the Expression.getVariables() will return a Map with one variable for the name a.

It is possible to not allow undefined global variables by using the ExpressionJ.acceptUndefinedVariables(boolean) method. For example, the following code will throw a ParseException:

      ExpressionJ.acceptUndefinedVariables(false);  
      Equation equation = ExpressionJ.parse("a = 2; return a + 1;");  

Notes

  1. ^ Alternatively, you can also use the parsexxx static methods of the EquationParser class

Categories: concepts

Copyright 2018 Herve Girod. All Rights Reserved