【问题标题】:Java replaceAll ' with '' except first and last occurrenceJava replaceAll ' with '' 除了第一次和最后一次出现
【发布时间】:2019-09-10 07:00:17
【问题描述】:

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

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

我来了

''123''456'

如何获得

'123''456'

谢谢。

【问题讨论】:

  • 您是否要转义 SQL 的值?
  • 也许你可以用两个替换所有单引号,然后删除第一个和最后一个单引号?
  • replaced.substring(0,1) 删除第一个字符怎么样,因为你已经声明你排除了最后一个字符
  • @kayaman 是的,我是 sql 转义字符串
  • @Meesh 然后停止你正在做的事情。手动转义值是没有用的,而使用正则表达式来做这件事既复杂又没用。使用PreparedStatement.setString(),它将逃避一切必要的事情。那么你也不需要开头和结尾的'

标签: java replaceall


【解决方案1】:
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));

【讨论】:

  • 避免字符串连接,使用 StringBuilder.add 代替。很好的解决方案
  • 为此我认为使用字符串连接没有任何问题,我猜这里使用 StringBuilder 是一个过早的优化。
  • 对,@RuelosJoel,可能是我讨厌太多的字符串连接
【解决方案2】:

关于正则表达式和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();

【讨论】:

    【解决方案3】:

    正则表达式: (?

    它将帮助您找出结果,然后您可以替换它。

    【讨论】:

      【解决方案4】:

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

            // 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");
            }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-07
        • 1970-01-01
        • 2020-08-30
        • 2016-05-10
        • 1970-01-01
        • 1970-01-01
        • 2013-12-28
        • 1970-01-01
        相关资源
        最近更新 更多