Search code examples
javareplaceall

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.


Solution

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