Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java replaceAll ' with '' except first and last occurrence

I want to replace all occurrences of single quotations with two quotations, except in first and last occurrence, I managed to get to exclude the last occurrence using regex as follows

String toReplace = "'123'456'";
String regex = "'(?=.*')";
String replaced = toReplace.replaceAll(regex,"''");
System.out.println(replaced);

Here I get

''123''456'

How do I get

'123''456'

Thank you.

like image 631
Meesh Avatar asked Sep 08 '26 23:09

Meesh


2 Answers

There is a pithy saying about regular expressions and two problems, but I'll skip that and suggest you simplify this by using a StringBuilder; find the index of both the first ' and the last ' in your input, then iterate between those indices looking for ' (and replacing with ''). Something like,

StringBuilder sb = new StringBuilder(toReplace);
int first = toReplace.indexOf("'"), last = toReplace.lastIndexOf("'");
if (first != last) {
    for (int i = first + 1; i < last; i++) {
        if (sb.charAt(i) == '\'') {
            sb.insert(i, '\'');
            i++;
        }
    }
}
toReplace = sb.toString();
like image 172
Elliott Frisch Avatar answered Sep 11 '26 13:09

Elliott Frisch


int first = toReplace.indexOf("'") + 1;
int last = toReplace.lastIndexOf("'");

String afterReplace = toReplace.substring(0, first)
        + toReplace.substring( first,last ).replaceAll("'", "''")
        + toReplace.substring(last);

System.out.println(afterReplace);

With StringBuilder

String afterReplace = new StringBuilder()
        .append(toReplace, 0, first)
        .append(toReplace.substring(first, last).replaceAll("'", "''"))
        .append(toReplace, last, toReplace.length())
        .toString();

Or with String.format

String afterReplace = String.format("%s%s%s",
        toReplace.substring(0, first),
        toReplace.substring(first, last).replaceAll("'", "''"),
        toReplace.substring(last));
like image 26
lczapski Avatar answered Sep 11 '26 12:09

lczapski