split 分割 字串(分隔符如:* ^ : | , .) 及注意點
阿新 • • 發佈:2019-02-17
【1】單個符號作為分隔符
String address=”上海|上海市|閔行區|吳中路”;
String[] splitAddress=address.split(“\|”); //如果以豎線為分隔符,則split的時候需要加上兩個斜槓【\】進行轉義
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
String address="上海*上海市*閔行區*吳中路"; String[] splitAddress=address.split("\\*"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); String address="上海:上海市:閔行區:吳中路"; String[] splitAddress=address.split("\:"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); String address="上海.上海市.閔行區.吳中路"; String[] splitAddress=address.split("\\."); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); String address="上海^上海市^閔行區^吳中路"; String[] splitAddress=address.split("\\^"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); String address="上海@上海市@閔行區@吳中路"; String[] splitAddress=address.split("@"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); String address="上海,上海市,閔行區,吳中路"; String[] splitAddress=address.split(","); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]); 【2】多個符號作為分隔符 String address="上海^上海市@閔行區#吳中路"; String[] splitAddress=address.split("\\^|@|#"); System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
*****************格式 小提示*****************************************
String address = new String(“192.168.13.240”);
String[] str = address.split(“\.”);
for(String s : str){
System.out.println(s);
}
輸出格式:
192
168
13
240
System.out.println(splitAddress[0]+splitAddress[1]+splitAddress[2]+splitAddress[3]);
輸出格式:上海上海市閔行區吳中路
總結:(1)split表示式,其實就是一個正則表示式。* ^ | 等符號在正則表示式中屬於一種有特殊含義的字元,如果使用此種字元作為分隔符,必須使用轉義符即\加以轉義。
(2)如果使用多個分隔符則需要藉助 | 符號,如【2】所示,但需要轉義符的仍然要加上分隔符進行處理。