一、split介绍
split() 方法根据匹配给定的正则表达式来拆分字符串。
注意: . 、 $、 | 和 * 等转义字符,必须得加 \\。
注意:多个分隔符,可以用 | 作为连字符。
语法
public String[] split(String regex, int limit)
参数
- regex -- 正则表达式分隔符。
- limit -- 分割的份数。
返回值
二、测试一
如下示例,猜猜答案吧
private static void test01() { String str1="a"; String str2="a,b"; String str3="a,b,"; String str4="a,b, "; String str5=",,,,,,"; String[] split1 = str1.split(","); String[] split2 = str2.split(","); String[] split3 = str3.split(","); String[] split4 = str4.split(","); String[] split5 = str5.split(","); System.out.println("str1分割后:"+JSON.toJSONString(split1)); System.out.println("str2分割后:"+JSON.toJSONString(split2)); System.out.println("str3分割后:"+JSON.toJSONString(split3)); System.out.println("str4分割后:"+JSON.toJSONString(split4)); System.out.println("str5分割后:"+JSON.toJSONString(split5)); }
结果
str1分割后:["a"] str2分割后:["a","b"] str3分割后:["a","b"] str4分割后:["a","b"," "] str5分割后:[]
三、测试二
private static void test02() { String str1="a"; String str2="a,b"; String str3="a,b,"; String str4="a,b, "; String str5=",,,,,,"; String[] split1 = str1.split(",",2); String[] split2 = str2.split(",",2); String[] split3 = str3.split(",",2); String[] split4 = str4.split(",",2); String[] split5 = str5.split(",",2); System.out.println("str1分割后:"+JSON.toJSONString(split1)); System.out.println("str2分割后:"+JSON.toJSONString(split2)); System.out.println("str3分割后:"+JSON.toJSONString(split3)); System.out.println("str4分割后:"+JSON.toJSONString(split4)); System.out.println("str5分割后:"+JSON.toJSONString(split5)); }
结果
str1分割后:["a"] str2分割后:["a","b"] str3分割后:["a","b,"] str4分割后:["a","b, "] str5分割后:["",",,,,,"]