關於Java中String類的split(String regex)方法的一點困惑

來源:互聯網
上載者:User

 關於Java中String類的split(String regex)方法的一點困惑

在JDK中文API裡面對這個類有如下描述:

public String[] split(String regex)

根據給定的Regex的匹配來拆分此字串。

該方法的作用就像是使用給定的運算式和限制參數 0 來調用兩參數 split 方法。因此,結果數組中不包括結尾Null 字元串。

例如,字串 "boo:and:foo" 產生帶有下面這些運算式的結果:

Regex

結果

:

{ "boo", "and", "foo" }

o

{ "b", "", ":and:f" }

 

 

參數:
regex - 定界Regex
返回:
字串數組,根據給定Regex的匹配來拆分此字串,從而產生此數組。
拋出:
PatternSyntaxException - 如果Regex的文法無效
從以下版本開始:
1.4
另請參見:
Pattern

 

代碼如下:

String longString="aa:bb:cc";
     String[] shortString=longString.split(":");
     for(int i=0;i<shortString.length;i++){
      System.out.println (shortString[i]);
     }

得到:aa、bb、cc。

可以證明沒有問題,可是如果longString="aa|bb|cc",就有問題了,代碼如下:

String longString="aa|bb|cc";
     String[] shortString=longString.split("|");
     for(int i=0;i<shortString.length;i++){
      System.out.println (shortString[i]);
     }

則得到a、a、|、b、b、|、c、c,就有問題了,不知道是什麼原因。

聯繫我們

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