跳到主要内容

Java split() 方法


split() 方法根据匹配给定的正则表达式来拆分字符串。

注意: . 、 $ 、 | 和 * 等转义字符,必须得加 \

注意:多个分隔符,可以用 | 作为连字符。

语法

public String[] split(String regex, int limit)

参数

  • regex -- 正则表达式分隔符。

  • limit -- 分割的份数。

返回值

字符串数组。

实例

public class Test {
public static void main(String args[]) {
String str = new String("Welcome-to-Lectcode");

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.lectcode.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

Lectcode



- 分隔符设置分割份数返回值 :

Welcome

to-Lectcode



转义字符返回值 :

www

lectcode

com



多个分隔符返回值 :

acount=?

uu =?

n=?