我想分割從數據庫結果集行生成的以下字符串。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} [()\「] *」,「|」);' –