首页 > 代码库 > Replace和ReplaceAll的区别
Replace和ReplaceAll的区别
先澄清几个误区
1、CharSequence 不是 Char :有些小朋友根据参数的类型选择Replace或ReplaceAll方法2、Replace 和 ReplaceAll :并不是有些小朋友想象的Replace只替代一个出现的字符,ReplaceAll 替换所有字符
3、循环替换的误区String eventJson = "............."; Iterator<Entry<String, String>> itPro = map.entrySet().iterator(); while (itPro.hasNext()) { Entry<String, String> entry = itPro.next(); eventJson.replace(entry.getKey(), entry.getValue()); } System.out.println(eventJson);上面伪代码并不能得到你想要的结果。
eventJson.replace(entry.getKey(), entry.getValue()); 需要替换成 eventJson = eventJson.replace(entry.getKey(), entry.getValue());
不耐烦的同学现在一定急着想知道两者的区别呢,现在开始讲解:
你可以去看看两个方法的定义:String java.lang.String.replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".Parameters:
target The sequence of char values to be replaced
replacement The replacement sequence of char values
Returns:
The resulting string
Throws:
NullPointerException - iftarget orreplacement is null.
Since:
1.5
String java.lang.String.replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement. An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use java.util.regex.Matcher.quoteReplacement to suppress the special meaning of these characters, if desired.Parameters:regex the regular expression to which this string is to be matchedreplacement the string to be substituted for each matchReturns:The resulting StringThrows:PatternSyntaxException - if the regular expression‘s syntax is invalidSince:1.4See Also:java.util.regex.Pattern@specJSR-51一目了然!
String.Replace 主要是针对字符串的替换。String.ReplaceAll 主要是用正则表达式的子字符串进行替换。
我们做个测试看看!System.out.println("1234567890abcdef".replace("12345", "ABCDE")); System.out.println("1234567890abcdef".replaceAll("12345", "ABCDE")); System.out.println("!@#$%^&*()-=Abcd".replace("#$%^&", "OK")); System.out.println("!@#$%^&*()-=Abcd".replaceAll("#$%^&", "OK"));执行结果!
ABCDE67890abcdef ABCDE67890abcdef !@OK*()-=Abcd !@#$%^&*()-=Abcd明显最后一行替换失败了,因为有正则表达式字符!
追求性能的同学一定会问这两个方法谁快,这个就留个好奇的你了,呵呵...
这边没时间做大量的测试给你求证了,但是给出不严谨的个人猜想如下:Replace比ReplaceAll性能略好。
但是有正则匹配的时候你肯定选用ReplaceAll了。希望有时间的同学提供性能方面的比较哦!谢谢!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。