I want to replace all occurrences of backslash char in my string to " char. But in one condition, for the first and last occurrences of backslash, I want it to be replaced differently for first and last occurrences.
String as example:
id_123,balance_account,\openDate\:\600\
Should be changed to:
id_123,balance_account,{"openDate":"600"}
As you can see, I want to replace the first and last appearance of the backslash in the string, to the new pattern, which consists of 2 chars:
In first occurrence: {"
In last occurrence: "}
>Solution :
String input = "id_123,balance_account,\\openDate\\:\\600\\";
Pattern p = Pattern.compile("\\\\");
Matcher m = p.matcher(input);
StringBuilder sb = new StringBuilder();
if (m.find()) {
m.appendReplacement(sb, "{\"");
while (m.find()) {
m.appendReplacement(sb, "\"");
}
sb.append("}");
m.appendTail(sb);
}