Java logical expression splitting

How to split a boolean expression in Java? For example, I want to get the a_1 & b_2 | (!c_3)following from an expression :

String tokens[] = {"a_1", "&", "b_2", "|", "(", "!", "c_3", ")"};

Variable names contain alphanumeric characters and underscores ( _).

+3
source share
2 answers

If you

String str = "a & b | (!c)";

get rid of spaces first:

String str2 = str.replaceAll(" ", "");

then get the array you want:

String[] array = str2.split("");

Update : based on a modified OP question, the following solution:

String str = "a_1 & b_2 | (!c_3)";  // initial string

StringCharacterIterator sci = new StringCharacterIterator(str);  // we use a string iterator for iterating over each character

List<String> strings = new ArrayList<String>();  // this will be our array of strings in the end

StringBuilder sb = new StringBuilder();  // a string builder for efficiency

for(char c = sci.first(); c != sci.DONE; c = sci.next()) {
    if( c == ' ' ) {
        continue;  // we ignore empty spaces
    }


    else if( 
        c == '&' ||
        c == '(' ||
        c == ')' ||
        c == '|' ||
        c == '!') 
    {
        // if we stumble upon one of 'tokens', we first add any previous strings that are variables to our string array, then add the token and finally clean our StringBuilder

        if(sb.length() != 0) strings.add(sb.toString());
        strings.add(String.valueOf(c));
        sb = new StringBuilder();
    }
    else {
        sb.append(c);  // we have a character that part of a variable
    }

}



String[] finalArray = strings.toArray(new String[0]);  // we turn our list to an array

for (String string : finalArray) {
    System.out.println(string);  // prints out everything in our array
}
+1
source

If you want to parse String - perhaps create a syntax tree and evaluate the expression - then it is better to parse String with a simple switch statement:

// for each char c in String
switch (c) {
  case '&': processAnd();break;
  case '|': processOr();break;
  case '!': processNot();break;
  case '(': processOpenPara();break;
  case ')': processClosePara();break;
  case ' ': break;
  default:  processVarName(); break;
}

This is just a stub to show the pattern. You can use the stack to evaluate an expression.

+5
source

Source: https://habr.com/ru/post/1783400/


All Articles