2009-12-22 7 views
0
나는이 쉼표 + 인용 문자열의 집합으로 문자열을 구분 분할 할 방법

:정규식 (자바)의 도움

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

출력 결과는 항상 'String 1'과 'String, two'가됩니다. 나는 쉼표로 구분하고, 묶인 필드를 인용했습니다. 따옴표는 선택 또는 필수입니까? – jabbie

답변

1

가되기 위해 :

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

당신은 사용할 수 있습니다

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

나는 이것으로 끝났다. 그것은 대부분의 정규식으로 추한,하지만 효과적이고 내 옵션이 제한되어 있습니다 : String noBrackets = StringUtils.substringBetween (test, "[\" ","\ "]"); String [] results = noBrackets.split ("\", [] * \ ""); – emulcahy

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를 구문 분석하기 위해 많은 오픈 소스 소규모 라이브러리 중 하나를 사용할 수도 있습니다. opencsv 또는 Commons CSV입니다.