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.
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();
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With