我知道有两种方法可以替换字符串中所有子串的出现。
I know of two ways of replacing all occurrences of substring in a string.
正则表达式方式(假设substring-to-被替换不包括正则表达式特殊字符:
The regex way (assuming "substring-to-be-replaced" doesn't include regex special chars):
String regex = "substring-to-be-replaced" + "+"; Pattern scriptPattern = Patternpile(regex); Matcher matcher = scriptPattern.matcher(originalstring); newstring = matcher.replaceAll("replacement-substring");String.replace()方式:
The String.replace() way:
newstring = originalstring.replace("substring-to-be-replaced", "replacement-substring");两者中哪一个更有效(以及为什么)?
Which of the two is more efficient (and why)?
是否有比上述两种更有效的方式?
Are there more efficient ways than the above described two?
推荐答案String.replace() 使用下面的正则表达式。
String.replace() uses regex underneath.
public String replace(CharSequence target, CharSequence replacement) { return Patternpile(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.
更多推荐
替换字符串中出现的所有子字符串
发布评论