本文共 1558 字,大约阅读时间需要 5 分钟。
在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("\\*"); 这样才能得到正确的结果
3、如果想在串中使用"\"字符,则也需要转义.首先要表达"aaaa\bbbb"这个串就应该用"aaaa\\bbbb",如果要分隔就应该这样才能得到正确结果: String[] aa = "aaa\\bbb\\bccc".split("\\\\");String.split()方法的jdk
[] java.lang. .split( regex)
Splits this string around matches of the given .
This method works as if by invoking the two-argument 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:
- - if the regular expression's syntax is invalid Since:
- 1.4 See Also:
- @spec
- JSR-51
转载地址:https://blog.csdn.net/courage89/article/details/9055317 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!