homjava String.split()函數的用法分
在java.lang包中有String.split()方法的原型是:
public String[] split(String regex, int limit)
split函數是用於使用特定的切割符(regex)來分隔字串成一個字串數組,函數返回是一個數組。在其中每個出現regex的位置都要進行分解。
需要注意是有以下幾點:
(1)regex是可選項。字串或Regex對象,它標識了分隔字串時使用的是一個還是多個字元。如果忽略該選項,返回包含整個字串的單一元素數組。
(2)limit也是可選項。該值用來限制返回數組中的元素個數。
(3)要注意逸出字元:“.”和“|”都是逸出字元,必須得加"\\"。同理:*和+也是如此的。
如果用“.”作為分隔的話,必須是如下寫法:
String.split("\\."),這樣才能正確的分隔開,不能用String.split(".");
如果用“|”作為分隔的話,必須是如下寫法:
String.split("\\|"),這樣才能正確的分隔開,不能用String.split("|");
(4)如果在一個字串中有多個分隔字元,可以用“|”作為連字號,比如:“acountId=? and act_id =? or extra=?”,把三個都分隔出來,可以用
String.split("and|or");
(5)split函數結果與regex密切相關,常見的幾種情況如下所示:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public class SplitTest { public static void main ( String [ ] args ) { String str1 = "a-b" ; String str2 = "a-b-" ; String str3 = "-a-b" ; String str4 = "-a-b-" ; String str5 = "a" ; String str6 = "-" ; String str7 = "--" ; |