Dear Reader,
Recently we have noticed when we do String.replace API call in Java, the replacement doesn't behave the same way
strings having multiple zeroes. Example if we want to replace "aa" with "Z" and String is "aa bb aaa", replaced
String will be "Z bb Za". However if we want replacement to happen only when exact word is met: use \\baa\\b.
This \\b works as Word boundary, however the same logic does not work in below program.
Plz refer screenshot.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ReplaceString {
public static void main(String[] args) {
Map <String, String> map = new HashMap<String, String>();
map.put("#{TxnAmount} == 200000","1.0");
map.put("#{TxnAmount} == 2000000","0.0");
Iterator it = map.keySet().iterator();
String expression ="#{TxnAmount} == 200000 || #{TxnAmount} == 2000000";
while (it.hasNext()) {
String key = (String) it.next();
String value = (String) map.get(key);
System.out.println("Key: "+key);
expression = expression.replace(key, value);
}
System.out.println("1. Final expression: "+expression);
map.clear();
map.put("#{TxnAmount} == 300000","1.0");
map.put("#{TxnAmount} == 3000000","0.0");
it = map.keySet().iterator();
expression ="#{TxnAmount} == 300000 || #{TxnAmount} == 3000000";
while (it.hasNext()) {
String key = (String) it.next();
String value = (String) map.get(key);
System.out.println("Key: "+key);
expression = expression.replace(key, value);
}
System.out.println("2. Final expression: "+expression);
}
}
Tuesday, March 6, 2018
String replace issue in JDK 1.7 and 1.8
Subscribe to:
Posts (Atom)