I am trying to parse an expression to find out some reserved operators/strings and replace them with corresponding numeric values , which are stored in a hashmap, and display the resultant expression which has numeric values instead of the reserved strings. This is what I am trying to do:
String expression = "SUM_ALL(4:5,5:6)>MAX(6:7)";
Map<String, Double> functionOperators = new HashMap<String,Double>();
functionOperators.put("SUM_ALL(4:5,5:6)", 4.0);
functionOperators.put("MAX(6:7)",5.0);
expression = expression.replaceAll("(SUM_ALL|MAX)\\s*\\(\\s*([\\d:,]+)\\s*\\)",
Double.toString(functionOperators.get(String.format("%s(%s)","$1","$2"))));
System.out.println(expression);
"$1" and "$2" are used to back reference the groups in the expression.
Here is the output of the same:
Exception in thread "main" java.lang.NullPointerException
whereas when I remove the fetching part (from the hashmap) and instead limit it to just a string change using the back-referenced groups, it works just fine.
expression = expression.replaceAll("(SUM_ALL|MAX)\\s*\\(\\s*([\\d:,]+)\\s*\\)",
String.format("%s|%s|","$1","$2"));
Output:
SUM_ALL|4:5,5:6|>MAX|6:7|
I suspect that while fetching the value from the hashmap, the "$1" and "$2" variables have still not been resolved by back-referencing and hence, it is not able to locate a key corresponding to the same.
If this is true, then what method do you suggest to implement my use case where I need the replacement value from a predefined hashmap.