2009-12-22 62 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