Reg*_*kie 10 java regex string
我知道有两种方法可以替换字符串中所有出现的子字符串.
正则表达式方式(假设"要替换的子字符串"不包括正则表达式特殊字符):
String regex = "substring-to-be-replaced" + "+";
Pattern scriptPattern = Pattern.compile(regex);
Matcher matcher = scriptPattern.matcher(originalstring);
newstring = matcher.replaceAll("replacement-substring");
Run Code Online (Sandbox Code Playgroud)
String.replace()方式:
newstring = originalstring.replace("substring-to-be-replaced", "replacement-substring");
Run Code Online (Sandbox Code Playgroud)
哪两个更有效(以及为什么)?
有没有比上述两种更有效的方法?
Joh*_*erg 13
String.replace() 在下面使用正则表达式.
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL)
.matcher(this ).replaceAll(
Matcher.quoteReplacement(replacement.toString()));
}
Run Code Online (Sandbox Code Playgroud)
有没有比上述两种更有效的方法?
您可以使用例如由数组支持的实现,而不是不可变的String类(因为在每次调用时string.replace创建一个新字符串).请参阅StringBuilder.replace().
编译正则表达式会产生很多开销,这在观察Pattern源代码时很明显.幸运的是,Apache提供了一种替代方法StringUtils.replace(),根据源代码(第3732行)非常有效.