替换字符串中所有出现的子字符串-在Java中哪个效率更高?


问题内容

我知道替换字符串中 所有 出现的子字符串的两种方法。

正则表达式的方式(假设“要替换的子字符串”不包括正则表达式的特殊字符):

String regex = "substring-to-be-replaced" + "+";
Pattern scriptPattern = Pattern.compile(regex);
Matcher matcher = scriptPattern.matcher(originalstring);
newstring = matcher.replaceAll("replacement-substring");

String.replace()方式:

newstring = originalstring.replace("substring-to-be-replaced", "replacement-substring");

两者中哪一个效率更高(为什么)?

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


问题答案:

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

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

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

假设您在一个由数组支持的实现上进行操作,而不是在不可变的String类上进行操作(因为每次调用string.replace都会创建一个 新的
字符串)。例如,参见StringBuilder.replace()

编译正则表达式会产生 很多 开销,这在观察Pattern源代码时很明显。幸运的是,Apache提供了一种替代方法StringUtils.replace(),根据源代码(第3372行),该方法非常有效。