2009-12-22 64 views
0

我如何拆分此逗號+引號分隔字符串轉換爲一組字符串:正則表達式(JAVA)的幫助

String test = "[\"String 1\",\"String, two\"]"; 
String[] embeddedStrings = test.split("<insert magic regex here>"); 
//note: It should also work for this string, with a space after the separating comma: "[\"String 1\", \"String, two\"]";  

assertEquals("String 1", embeddedStrings[0]); 
assertEquals("String, two", embeddedStrings[1]); 

我很好修剪方括號作爲第一步。但問題是,即使我這樣做了,我也不能只用逗號分割,因爲嵌入的字符串可以包含逗號。 也可以使用Apache的StringUtils。

+0

所以你的輸出將總是'串1'和'串,兩'?我想你有逗號分隔,引用封閉的字段。報價是可選的還是必需的? – jabbie 2009-12-22 21:31:17

回答

1

如果你能夠從外字符串的開頭和\"]從它的結尾處,刪除[\" 成爲:

 String test = "String 1\",\"String, two"; 

您可以使用:

 test.split("\",\""); 
+0

我結束了這個。這是醜陋的,因爲大多數正則表達式,但它是有效的,我的選擇是有限的: String noBrackets = StringUtils.substringBetween(test,「[\」「,」\「]」); String [] results = noBrackets.split(「\」,[] * \「」); – emulcahy 2009-12-22 21:35:25

0

這是非常脆弱的,應該避免,但你可以匹配字符串文字。

Pattern p = Pattern.compile("\"((?:[^\"]+|\\\\\")*)\""); 

String test = "[\"String 1\",\"String, two\"]"; 
Matcher m = p.matcher(test); 
ArrayList<String> embeddedStrings = new ArrayList<String>(); 
while (m.find()) { 
    embeddedStrings.add(m.group(1)); 
} 

的正則表達式假設輸入雙引號使用\"而不是""逃脫。如果輸入具有奇數的(未轉義的)雙引號,則該模式會中斷。

0

窮舉法,其中一些可能是僞代碼,我認爲在設置currStart和/或String.substring()時存在fencepost問題。這假定括號已經被刪除。

 
boolean inquote = false; 
List strings = new ArrayList(); 
int currStart=0; 
for (int i=0; i<test.length(); i++) { 
    char c = test.charAt(i); 
    if (c == ',' && ! inquote) { 
    strings.add(test.substring(currStart, i); 
    currStart = i; 
    } 
    else if (c == ' ' && currStart + == i) 
    currStart = i; // strip off spaces after a comma 
    else if (c == '"') 
    inquote != inquote; 
} 
strings.add(test.substring(currStart,i)); 
String embeddedStrings = strings.toArray(); 
3

您也可以使用許多開源小型庫中的一個來解析CSV,例如, opencsvCommons CSV