Reputation: 1033
My question might be little odd. I have below condition in String
String condition="((1 || 3) && 4)"; ***//I am fine to add special characters in this condition as well..***
In my code, I need to dynamically evaluate expression by replacing number values with ArrayList.get
as below:
boolean result=(someArrayList.get(1).isResult() || someArrayList.get(3).isResult()) && someArrayList.get(4).isResult();
My question is that, how can I easily replace numbers (1,3,4) in above condition with someArrayList.get(1)
... I can write logic to do it, but trying to see if there's any easy API to use it.
Upvotes: 0
Views: 354
Reputation: 140514
Just use replaceAll
:
String condition="((1 || 3) && 4)";
String newCondition = condition.replaceAll("(\\d+)", "someArrayList.get($1).isResult()");
((someArrayList.get(1).isResult() || someArrayList.get(3).isResult()) && someArrayList.get(4).isResult())
Upvotes: 1
Reputation: 79550
You can do it as follows:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String condition = "((1 || 3) && 4)";
StringBuilder sb = new StringBuilder(condition);
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(condition);
int index, fromIndex = 0, upTo;
while (m.find()) {
String num = m.group();
index = sb.indexOf(num, fromIndex);
upTo = index + num.length();
sb.replace(index, upTo, "someArrayList.get(" + num + ").isResult()");
fromIndex = upTo;
}
System.out.println(sb);
}
}
Output:
((someArrayList.get(1).isResult() || someArrayList.get(3).isResult()) && someArrayList.get(4).isResult())
Upvotes: 1