ExprTk, get a list of symbols/variables in expression
Asked Answered
B

1

8

I want to get a list of the symbols out of an expression in ExprTk (not the ones I registered, but the ones that are in the expression. E.g. when the expression is

const std::string expression_string = "abs(sin(x)^2+5*y)";

I need to get x and y as result as a list/vector or something. How can I do this?

Baikal answered 3/3, 2020 at 12:57 Comment(0)
S
10

In the ExprTk readme.txt: Section 23 - Helpers & Utils has the following helper free function: collect_variables

Usage is as follows:

  const std::string expression_string = "abs(sin(x)^2+5*y)";

  std::vector<std::string> variable_list;

  if (exprtk::collect_variables(expression_string, variable_list))
  {
     for (const auto& var : variable_list)
     {
        ...
     }
  }
  else
    printf("An error occurred.");

Note: If the expression is invalid for any reason collect_variables will return false.

Strongroom answered 4/3, 2020 at 9:40 Comment(4)
exprtk::collect_variables does not work with following expressions LANGUAGE in ('SPANISH' + 'ENGLISH' + 'URDU') and PROFICIENCY > 0 101_Courses > 100 Is there a limitation to it?Hoekstra
@MirzaTalha the expression is malformed, there is a missing operator in: "0 101_Courses" the error context produced post compile provides all the details you need to detect and resolve the issue.Strongroom
"the error context produced post compile provides all the details you need to detect and resolve the issue" How can I find the errors that caused this function to return false?Peggypegma
@Peggypegma once the compile method returns a false value, information pertaining about the errors, their nature and locations can be accessed via the error_count and get_error methods. More information and a detailed explanation can be found in the readme.txt in Section 21 - Compilation Errors. In short if you also want to know the errors encountered during collect_variables, one can simply implement a similar function that returns the errors.Strongroom

© 2022 - 2024 — McMap. All rights reserved.