且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

替换字符串中出现的所有子字符串 - 这在Java中更有效吗?

更新时间:2022-11-07 20:53:50

String.replace() 使用下面的正则表达式。

String.replace() uses regex underneath.

public String replace(CharSequence target, CharSequence replacement) {
      return Pattern.compile(target.toString(), Pattern.LITERAL)
             .matcher(this ).replaceAll(
               Matcher.quoteReplacement(replacement.toString()));
  }




是否有比上述更有效的方法两个?

Are there more efficient ways than the above described two?

有一个实现支持的实现,例如,数组,而不是不可变的String类(因为 string.replace 在每次调用时创建一个 new 字符串。例如,参见 StringBuilder.replace()

There are given that you operate on an implementation backed e.g., by an array, rather than the immutable String class (since string.replace creates a new string on each invocation). See for instance StringBuilder.replace().

编译正则表达式会产生相当很多的开销,这在观察模式源代码 。幸运的是,Apache在 StringUtils.replace() ,根据源代码(第3732行)非常有效。

Compiling a regex incurs quite alot of overhead which is clear when observing the Pattern source code. Luckily, Apache offers an alternative approach in StringUtils.replace() which according to the source code (line #3732) is quite efficient.