【发布时间】:2015-02-17 17:01:04
【问题描述】:
我试图用单词填充 ArrayList,但有时它会添加一个空字符,为什么?我怎样才能避免这种情况?
ArrayList<String> textAL = new ArrayList<String>();
String text = "This.IS(a) text example blah? bl:ah";
String regex = "[\\s\\?\\.,:;\\)\\(]";
String[] splittedText = text.split(regex);
for(int i = 0; i < splittedText.length; i++){
if(splittedText[i] != " "){ //ignore whitespace
textAL.add(splittedText[i]);
}
}
for(int i = 0; i < textAL.size(); i++){
System.out.println("t2(" + i + ") "+ textAL.get(i));
}
结果:
textAL(0) This
textAL(1) IS
textAL(2) a
textAL(3)
textAL(4) text
textAL(5) example
textAL(6) blah
textAL(7)
textAL(8) bl
textAL(9)
textAL(10) ah
【问题讨论】:
-
"[\\s\\?\\.,:;\\)\\(]+"?或"\\W+"? -
我敢打赌 split 方法引入了空字符串,其中两个分隔符彼此相邻(如果在开头和结尾匹配)
标签: java regex arraylist split