Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to replace all occurrences of a char in a string, but differently on first and last occurrences?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading