Java 除第一次和最后一次出现外,将所有“替换为”

Java replaceAll ' with '' except first and last occurrence

我想用两个引号替换所有出现的单引号,除了第一次出现和最后一次出现,我设法使用正则表达式排除了最后一次出现,如下所示

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

这里我得到

''123''456'

如何获得

'123''456'

谢谢。

关于正则表达式和 two problems 有一个精辟的说法,但我会跳过它并建议您使用 StringBuilder 来简化它;找到输入中第一个 ' 和最后一个 ' 的索引,然后在这些索引之间迭代以查找 '(并替换为 '')。像,

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

StringBuilder

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

String.format

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

正则表达式: (?<=')(. *)(?=')

It will help you to find out your result and then you can replace it.

这也可以通过正则表达式实现:

      // String to be scanned to find the pattern.
      String line = "'123'456'";
      String pattern = "(?>^')(.*)(?>'$)";

      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      if (m.find( )) {
         System.out.println("Found value: " + m.group(1) );
         String replaced = m.group(1).replaceAll("'","\"");
         System.out.println("replaced value: " + replaced );
      }else {
         System.out.println("NO MATCH");
      }