问题引出:用^拆分如下字符串:B0005433^1~6^01^0001~0002^1,120~2,135^1,1,1,1,1,1^1,1,1
jdk文档说明:
public String[] split(String regex)
根据给定的正则表达式的匹配来拆分此字符串。
该方法的作用是使用给定的表达式和限制参数0来调用两参数split方法。因此数组中不包括结尾空字符串。
例如:字符串"boo:and:foo"产生带有下面这些表达式的结果:
regex result
: {"boo","and","foo"}
o {"b","",":and:f"}
注:使用此方法时,limit默认是0。
public String[] split(String regex, int limit)
根据匹配给定的正则表达式来拆分此字符串。
此方法返回的数组包含此字符串的每个子字符串,这些子字符串由另一个匹配给定的表达式的子字符串终止或由字符串结束来终止。数组中的子字符串按它们在此字符串中的顺序排列。如果表达式不匹配输入的任何部分,则结果数组只具有一个元素,即此字符串。
limit 参数控制模式应用的次数,因此影响结果数组的长度。
limit > 0,则模式将被最多应用limit-1次,数组长度不会大于limit,而且数组的最后项将包含超出最后匹配的定界符的所有输入。
limit<0,则模式将被应用尽可能多的次数,而且数组可以是任意长度。
limit=0,则模式将被应用尽可能多的次数,数组可有任何长度,并且结尾空字符串将被丢弃。
例如:字符串"boo:and:foo"产生带有下面这些表达式的结果:
regex limit result
: 2 {"boo","and:foo"}
: 5 {"boo","and","foo"}
: -2 {"boo","and","foo"}
o 5 {"b","",":and:f","",""}
o -2 {"b","",":and:f","",""}
o 0 {"b","",":and:f"}
jdk源码:
public String[] split(String regex, int limit) {
return Pattern.compile(regex).split(this, limit);
}
//将给定的正则表达式编译到模式中。
//public static Pttern compile(String regex)
public static Pattern compile(String regex) {
return new Pattern(regex, 0);
}
private Pattern(String p, int f) {
pattern = p;
flags = f;
// Reset group index count
capturingGroupCount = 1;
localCount = 0;
if (pattern.length() > 0) {
compile();
} else {
root = new Start(lastAccept);
matchRoot = lastAccept;
}
}
我们可以看到该方法最终是使用的正则表达式来拆分的。具体的文档写的很清楚。请参考jdk开发文档。
public class Test {
public static void main(String[] args) {
String str = "B0005433^1~6^01^0001~0002^1,120~2,135^1,1,1,1,1,1^1,1,1";
System.out.println(Arrays.toString(Pattern.compile("[/p{^}]").split(str)));
}
}
注: 此写法会按照[、/、^三个字符来分割,所以我需要改成[{^}]或者\\^即可。
除了使用split()方法以外,我们还可以使用StringTokenizer来处理。
String xhrStr = "B0005433^1~6^01^0001~0002^1,120~2,135^1,1,1,1,1,1^1,1,1";
StringTokenizer toker = new StringTokenizer(xhrStr,"^");
String[] xhrArr = new String[toker.countTokens()];
int x = 0;
while(toker.hasMoreTokens()){
xhrArr[x] = toker.nextToken();
x++;
}
在java3编程思想中说:正则表达式取代了先前版本中所有与"用标记断开"相关的类。
在java4编程思想中就已经不提倡用 StringTokenizer 来解决了,支持用正则表达式来分割字符串。