天天看點

Replace和ReplaceAll的差別

先澄清幾個誤區

1、charsequence 不是 char :有些小朋友根據參數的類型選擇replace或replaceall方法

2、replace 和 replaceall :并不是有些小朋友想象的replace隻替代一個出現的字元,replaceall 替換所有字元

3、循環替換的誤區

上面僞代碼并不能得到你想要的結果。

不耐煩的同學現在一定急着想知道兩者的差別呢,現在開始講解:

你可以去看看兩個方法的定義:

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 主要是用正規表達式的子字元串進行替換。

我們做個測試看看!

執行結果!

明顯最後一行替換失敗了,因為有正規表達式字元!

追求性能的同學一定會問這兩個方法誰快,這個就留個好奇的你了,呵呵...

這邊沒時間做大量的測試給你求證了,但是給出不嚴謹的個人猜想如下:

replace比replaceall性能略好。

但是有正則比對的時候你肯定選用replaceall了。

希望有時間的同學提供性能方面的比較哦!謝謝!