jdk中String對象的replace和replaceAll方法

來源:互聯網
上載者:User
java作為目前最受開發人員歡迎以及熱度最高的一門語言,在很多方面展現出了其特性,雖然靈活性不比c++,執行效率不比c,開發效率不比Ruby,但是作為最早最純粹的OO語言,java在目前來說因為其在編程方面有著與c及c++語言的延續性而被廣泛的使用。即使java是如此的受歡迎,個人覺得jdk的api在很多方面卻做的不是太好,簡單的以命名來說。比如說string類的兩個方法replace和replaceAll,因為有replaceAll的存在根據命名來看很容易使人覺得第一個replace方法是用replacement字串替換source字串中第一個出現的target字串,而replaceAll方法是替換在source字串中所出現的所有target字串。
至少在jdk中它們是這樣聲明的:public String replaceAll(String regex, String replacement) {...}

public String replace(CharSequence target, CharSequence replacement){...}
如果不去閱讀它們的注釋或者查看具體實現,你自然的覺得它們二者就只是存在著替換數量之間的差別,一個是全部替換,另外一個只是替換第一個(至少我是這樣理解的,並且在此api上面也吃過一些虧)。二者的注釋分別為:replaceAll Replaces each substring of this string that matches the given
regular expression with the given replacement.replaceReplaces 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".到此才得知replaceAll是採用Regex進行文本的替換,替換所有滿足條件的substring。replace是採用文本本身的內容進行匹配替換,也是所有滿足條件的substring。
例如下面的代碼:
                String info = "catfish+foolishcat";String withReplace = info.replace("catfish+", "rxr");String withReplaceAll = info.replaceAll("catfish+", "rxr");System.out.println("withReplace    is " + withReplace);System.out.println("withReplaceAll is " + withReplaceAll);

最後的輸出分別為:

withReplace    is rxrfoolishcat
withReplaceAll is rxr+foolishcat所以這兩個方法在命名上面給開發人員的歧義性太大,不具備可讀性,至少不能望文生義,replace替換成replaceWithLiteralTarget,replaceAll替換成replaceWithRegexTarget能夠從語義上面區分出二者的差別。針對replace和replaceAll命名的就說這麼多,有時間把個人認為jdk中不好的一些define都拿出來記錄一下,以免以後犯同樣的錯誤。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.