Question
Cognizant
IN
Last activity: 27 Mar 2025 14:01 EDT
Identify operator position in a logical string
Hello Team,
I got a requirement, Logical string of a when rule is " E1 OR E2 AND E3 " and i want to convert into like this " &(|(E1,E2),E3) ". So identifying the operator from left to right in a logical string and replace the operator with comma i.e , and add the same operator with symbol notation in left side of the sting. How can i achieve this ? Is there any function to identify ? Pls share your thoughts on this.
Thanks in Advance..!
Hi @Ravi prasad
There is no specific function for the requirement you mentioned.
Try to create the function and give the code as below.
public static String convertLogicalString(String input) {
if (input == null || input.isEmpty()) {
return "";
}
input = input.replaceAll("\\s+", ""); // Remove spaces
String[] parts = input.split("((?<=AND)|(?=AND)|(?<=OR)|(?=OR))");
StringBuilder result = new StringBuilder();
String lastOperator = "";
for (String part : parts) {
if (part.equals("AND") || part.equals("OR")) {
lastOperator = part.equals("AND") ? "&" : "|";
} else {
if (result.length() == 0) {
result.append(lastOperator).append("(").append(part);
} else {
result.append(",").append(part);
}
}
}
result.append(")");
return result.toString();
}