How can I split a boolean expression in Java? For example, I want to get the following from the expression a_1 & b_2 | (!c_3)
a_1 & b_2 | (!c_3)
:
String tokens[] = {"a_1", "&", "b_2", "|", "(", "!", "c_3", ")"};
The names of the variables contain alphanumeric characters and underscores ( _
).
If you want to parse the String - maybe to create a syntax tree and evaluate the expression -, then it's better to parse the String with a simple switch expression:
// 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 may want to use a stack to evaluate the expression.
If you have
String str = "a & b | (!c)";
first, get rid of spaces:
String str2 = str.replaceAll(" ", "");
then, obtain the array you want like this:
String[] array = str2.split("");
Update : based on OP's changed question, another solution follows:
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's 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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.