Posted in Salesforce

Salesforce Apex : Evaluate Boolean String Expression


Wondering how to evaluate this expression which is a string using Apex?

Following class can be used to evaluate:

How to use?

This static method can be called as:

BooleanExpression.eval('(FALSE AND ((TRUE OR FALSE) AND (TRUE OR FALSE)))');

How it evolved?

While replicating the logic of Assignment Rule in Salesforce lightning, needed a way to implement Filter Logic like, 1 AND ( 2 OR 3 ) . Added few more to the above to achieve.

What is added to replicate Filter Logic in Assignment Rule?

Added a method:

 * Substitue numbers in expression with values based on the index	
public static String substituteValues(String expression, Boolean[] values) {
    String[] arguments = expression.split(' ');
    for(String arg : arguments) {
        try {
            Integer index = Integer.valueOf(arg.replaceAll('[^0-9]', ''));
            expression = expression.replaceAll(String.valueOf(index), String.valueOf(values[index - 1]));    
        } catch(Exception e) {}
    return expression;

Call the method in eval(), and added another argument for accepting values as list. Updated eval() method would be:

 * Evaluate a boolean expreassion 
public static Boolean eval(String expression, Boolean[] values) {
    expression = substituteValues(expression.toUpperCase(), values);
    // If expression contains all true or false
    if(expression.containsNone('false')) { return true; }        
    if(expression.containsNone('true')) { return false; }
    return Boolean.valueOf(evaluateExpression(expression));

To invoke,

List values = new List {
	true, false, true

BooleanExpession.eval('1 AND (2 OR 4)', values);

One thought on “Salesforce Apex : Evaluate Boolean String Expression

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s