在java.lang包中有String.split()方法,返回是一个数组,
1、如果用“.”作为分隔的话,必须是如下写法:String.split("\\."),这样才能正确的分隔开,不能用String.split(".");
2、如果用“|”作为分隔的话,必须是如下写法:String.split("\\|"),这样才能正确的分隔开,不能用String.split("|"); “.”和“|”都是转义字符,必须得加"\\";
3、如果在一个字符串中有多个分隔符,可以用“|”作为连字符,比如:“acount=? and uu =? or n=?”,把三个都分隔出来,可以用String.split("and|or"); 使用String.split方法分隔字符串时,分隔符如果用到一些特殊字符,可能会得不到我们预期的结果
举例:
1、参数regex是一个 regular-expression的匹配模式而不是一个简单的String,他对一些特殊的字符可能会出现你预想不到的结果,比如测试下面的代码: 用竖线 | 分隔字符串,你将得不到预期的结果 String[] aa = "aaa|bbb|ccc".split("|"); //String[] aa = "aaa|bbb|ccc".split("\\|"); 这样才能得到正确的结果
2、用竖 * 分隔字符串运行将抛出java.util.regex.PatternSyntaxException异常,用加号 + 也是如此。 String[] aa = "aaa*bbb*ccc".split("*"); //String[] aa = "aaa|bbb|ccc".split("\\*"); 这样才能得到正确的结果
String.split()方法的jdk
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split
method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
The string "boo:and:foo", for example, yields the following results with these expressions:
Regex Result : { "boo", "and", "foo" } o { "b", "", ":and:f" }
-
Parameters:
- regex the delimiting regular expression Returns:
- the array of strings computed by splitting this string around matches of the given regular expression Throws:
- PatternSyntaxException - if the regular expression's syntax is invalid Since:
- 1.4 See Also:
- java.util.regex.Pattern @spec
- JSR-51