Java split() 方法
今天在写SSM项目中碰到一个疑惑:
if(provider.getCompanyLicPicPath() != null && !"".equals(provider.getCompanyLicPicPath())){
String[] paths = provider.getCompanyLicPicPath().split("\\"+File.separator);
logger.debug("view companyLicPicPath paths[paths.length-1]============ " + paths[paths.length-1]);
provider.setCompanyLicPicPath(request.getContextPath()+"/statics/uploadfiles/"+paths[paths.length-1]);
}
在代码中split() 方法是用来干嘛的。
重点
split() 方法根据匹配给定的正则表达式来拆分字符串。
注意: . 、 $、 | 和 * 等转义字符,必须得加 \ \ ;
注意:多个分隔符,可以用 | 作为连字符。
语法
public String[] split(String regex, int limit)
参数
regex – 正则表达式分隔符。
limit – 分割的份数。
上面代码只运用了regex参数
实例
public class Test {
public static void main(String args[]) {
String str = new String("Welcome-to-Runoob");
System.out.println("- 分隔符返回值 :" );
for (String retval: str.split("-")){
System.out.println(retval);
}
System.out.println("");
System.out.println("- 分隔符设置分割份数返回值 :" );
for (String retval: str.split("-", 2)){
System.out.println(retval);
}
System.out.println("");
String str2 = new String("www.runoob.com");
System.out.println("转义字符返回值 :" );
for (String retval: str2.split("\\.", 3)){
System.out.println(retval);
}
System.out.println("");
String str3 = new String("acount=? and uu =? or n=?");
System.out.println("多个分隔符返回值 :" );
for (String retval: str3.split("and|or")){
System.out.println(retval);
}
}
}
以上程序执行结果为:
- 分隔符返回值 :
Welcome
to
Runoob
- 分隔符设置分割份数返回值 :
Welcome
to-Runoob
转义字符返回值 :
www
runoob
com
多个分隔符返回值 :
acount=?
uu =?
n=?