Java replaceAll ' with '' except first and last occurrence

Meesh :

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.

Elliott Frisch :

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();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=140304&siteId=1