java.split();用法

來源:互聯網
上載者:User

標籤:param   pattern   generated   java   pat   his   規則   詳解   程式   

split用法詳解在java.lang包中有String.split()方法,返回是一個數組 
在應用中用到一些,給大家總結一下,僅供大家參考: 
1、如果用“.”作為分隔的話,必須是如下寫法:String.split("\\."),這樣才能正確的分隔開,不能用String.split("."); 
2、如果用“|”作為分隔的話,必須是如下寫法:String.split("\\|"),這樣才能正確的分隔開,不能用String.split("|"); 
“.”和“|”都是逸出字元,必須得加"\\"; 
3、如果在一個字串中有多個分隔字元,可以用“|”作為連字號,比如:“acount=? and uu =? or n=?”,把三個都分隔出來,可以用String.split("and|or"); 
測試程式如下:public class StringSplit { /** 
* @param args 
*/ 
public static void main(String[] args) { 
// TODO Auto-generated method stub 
String a="acount=? and uu =? or n=?"; 
String b[]=a.split("and|or"); 
for(int i=0;i<=b.length;i++) 

System.out.println(b[i]); 
}   }} 
輸出結果:acount=? 
uu =? 
n=? 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 
at com.ljj.string.StringSplit.main(StringSplit.java:14) 

No.3 


String.split方法 

使用String.split方法時要注意的問題在使用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 System.out.println("--"+aa); 
}用豎 * 分隔字串運行將拋出java.util.regex.PatternSyntaxException異常,用加號 + 也是如此。String[] aa = "aaa*bbb*ccc".split("*"); 
//String[] aa = "aaa|bbb|ccc".split("\\*"); 這樣才能得到正確的結果for (int i = 0 ; i System.out.println("--"+aa); 
}顯然,+ * 不是有效模式比對規則運算式,用"\\*" "\\+"轉義後即可得到正確的結果。"|" 分隔串時雖然能夠執行,但是卻不是預期的目的,"\\|"轉義後即可得到正確的結果。還有如果想在串中使用"\"字元,則也需要轉義.首先要表達"aaaa\bbbb"這個串就應該用"aaaa\\bbbb",如果要分隔就應該這樣才能得到正確結果:String[] aa = "aaa\\bbb\\bccc".split("\\\\");

java.split();用法

聯繫我們

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