使用String.split方法時要注意的問題

來源:互聯網
上載者:User

在使用String.split方法分隔字串時,分隔字元如果用到一些特殊字元,可能會得不到我們預期的結果。

我們看jdk doc中說明

public String[] split(String regex)

 Splits this string around matches of the given regular expression. 

參數regex是一個 regular-expression的匹配模式而不是一個簡單的String,他對一些特殊的字元可能會出現你預想不到的結果,比如測試下面的代碼:

用豎線 | 分隔字串,你將得不到預期的結果

    String[] aa = "aaa|bbb|ccc".split("|");
    //String[] aa = "aaa|bbb|ccc".split("//|"); 這樣才能得到正確的結果

    for (int i = 0 ; i <aa.length ; i++ ) {
      System.out.println("--"+aa[i]);
    }

用豎 * 分隔字串運行將拋出java.util.regex.PatternSyntaxException異常,用加號 + 也是如此。

    String[] aa = "aaa*bbb*ccc".split("*");
    //String[] aa = "aaa|bbb|ccc".split("//*"); 這樣才能得到正確的結果   

    for (int i = 0 ; i <aa.length ; i++ ) {
      System.out.println("--"+aa[i]);
    }

顯然,+ * 不是有效模式比對規則運算式,用"//*" "//+"轉義後即可得到正確的結果。

"|" 分隔串時雖然能夠執行,但是卻不是預期的目的,"//|"轉義後即可得到正確的結果。

還有如果想在串中使用"/"字元,則也需要轉義.首先要表達"aaaa/bbbb"這個串就應該用"aaaa//bbbb",如果要分隔就應該這樣才能得到正確結果:

String[] aa = "aaa//bbb//bccc".split("////");

由於本人對regular-expression理解程度不深,還望高手指正、補充。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.