我想分割从数据库结果集行生成的以下字符串。Java字符串split()分隔符为零长度值
样品行:
A)(74 “并有”, “是一个汽车”, “中”, “车库的人”,T)
B)(17,account3, ,,,吨)
我想要的输出如下(管|分离分割元素):
A)74 |并在那里是汽车|在|中车库人| t
B)17 | account3 | | | | t
我想在我的应用程序中将零长度值存储为null。这是我的源代码:
public void refreshSearchTable (ArrayList<String> newData){
int noOfRows = newData.size();
int noOfColumns = gui.getTableSearchResultHeader().length + 1;
Object[][] tempList = new Object[noOfRows][noOfColumns];
String rowResult = "";
String delims = "[,()\"]+";
String [] tokens;
Object [] elements = newData.toArray();
int j = 0;
for (int i = 0; i < noOfRows; i++){
rowResult = elements[i].toString();
System.out.println("rowresult: " + rowResult);
tokens = rowResult.split(delims, -1);
for (String t : tokens){
System.out.println("j: " + j + "t: " + t);
if (j == 1){ ... }
else if (j==2){ ... }
...
j++;
}
j=0;
}
}
“[()\”]为非零长度值+”工作得很好,我能够根据索引值j拿起右边的子串。我已经读过,通过一个负值分割(,)将不会丢弃非零长度值...但它确实。我在做什么错?
这个效果很好!唯一的问题是在要拆分的字符串的开始和结尾处的开头和结尾括号出现在第一个和最后一个拆分元素中。 'rowresult:(74,“and there”,“is a car”,“in the”,“garage man”,t) j:0t:(74 j:1t:and there j:2t:is a汽车 j:3t:在 j:4t:车库人 j:5t:t)' – greatkalu
不能手动删除此括号吗?例如: if(str.startsWith(“(”))str = str.substring(1);和 if(str.endsWith(“)”))str = str.substring(0,str.length ()-1);'执行拆分之前? –
也许你可以使用相同的策略使用替换,这将有助于一点...例如'字符串str =“(74,\”和那里\“,\”是一个汽车\“,\”在\ “,”车库男子“,t)”; if(str.startsWith(“(”))str = str.substring(1); if(str.endsWith(“)”))str = str.substring(0,str.length() - 1); String result = str.replaceAll(“[()\”] *,{1} [()\“] *”,“|”);' –