2013-08-15 3 views
0

모든 쉼표를 java의 큰 따옴표 안에있는 하나의 특수 문자 (예 : "#")로 바꾸려고합니다. 내가 할 문자열의 첫 번째 차례 나오는 찾기 위해 위의 코드를 사용하여java Regex를 사용하여 문자열의 쉼표를 문자열로 바꾸기

public class Str { 
    public static void main(String[] args) { 
     String line="\"Lee, Rounded, Neck, Printed\",410.00,300.00,\"Red , Blue\",lee"; 
     String lineDelimiter=","; 
     String templine=line; 
     if(templine!=null && templine.contains("\"")) 
     { 
      Pattern p=Pattern.compile("(\".*?"+Pattern.quote(lineDelimiter)+".*?\")"); 
      Matcher m=p.matcher(templine); 
      if(m.find()) 
      { 
       for (int i = 1; i <= m.groupCount(); i++) { 
        String Temp=m.group(i); 
        String Temp1=Temp; 
        Temp=Temp.replaceAll("(,)", " ## "); 
        line=line.replaceAll(Pattern.quote(Temp1),Pattern.quote(Temp)); 
       } 
      } 
     } 
} 
} 

:

String line="\"Lee, Rounded, Neck, Printed\",410.00,300.00,\"Red , Blue\",lee"; 

출력 : 내가 시도

"Lee# Rounded# Neck# Printed",410.00,300.00,"Red # Blue",lee 

이 아래

은 문자열입니다 두 번째가 아닌 따옴표 안의 내용 ("Red, Blue").

+0

을 당신은하지 않습니다 Regex가 간단한 문자 교체를 할 필요가 있으며 Regex를 사용하는 것도 어렵지 않습니다. 어떤 문제가 발생 했습니까? – Matthew

+3

포인트는 "큰 따옴표 안에"입니다. 그럼에도 불구하고 무엇을 시도 했습니까? –

+0

CSV 라이브러리 사용을 고려 했습니까? –

답변

2

다음 코드는 작동합니다 :

String line="\"Lee, Rounded, Neck, Printed\",410.00,300.00,\"Red , Blue\",lee"; 
String repl = line.replaceAll(",(?!(([^\"]*\"){2})*[^\"]*$)", "#"); 
System.out.println("Replaced => " + repl); 

출력 :

"Lee# Rounded# Neck# Printed",410.00,300.00,"Red # Blue",lee 

설명 :이 정규식은 기본적으로는 큰 따옴표도 수에 따라되지 않을 경우 쉼표와 일치하는 것을 의미한다. 즉, 큰 따옴표 안에 있으면 쉼표와 일치해야합니다.

PS : 불균형 큰 따옴표가없는 것으로 가정하고 이스케이프 된 큰 따옴표가없는 경우를 가정합니다.

0

보십시오이 또한

String line="\"Lee, Rounded, Neck, Printed\",410.00,300.00,\"Red , Blue\",lee"; 
    StringTokenizer st=new StringTokenizer(line,"\""); 
    List<String> list=new ArrayList<>(); 
    List<String> list2=new ArrayList<>(); 
    while (st.hasMoreTokens()){ 
     list.add(st.nextToken()); 
    } 
    Pattern p = Pattern.compile("\"([^\"]*)\""); 
    Matcher m = p.matcher(line); 
    StringBuilder sb=new StringBuilder(); 
    while (m.find()) { 
     list2.add(m.group(1)); 
    } 

    for(String i:list){ 
     if(list2.contains(i)){ 
      sb.append(i.replaceAll(",","#")); 
     }else{ 
      sb.append(i); 
     } 
    } 

    System.out.println(sb.toString()); 
0

제 (내가 그것을 테스트하지 않은 의미) 다음과 같은 작업을해야합니다 :

//Catches contents of quotes 
static final Pattern outer = Pattern.compile("\\\"[^\\\"]*\\\""); 

private String replaceCommasInsideQuotes(String s) { 
    StringBuilder bdr = new StringBuilder(s); 
    Matcher m = outer.matcher(bdr); 
    while (m.find()) { 
     bdr.replace(m.start(), m.end(), m.group().replaceAll(",", "#")); 
    } 
    return bdr.toString(); 
} 

또는 유사한

//Catches contents of quotes 
static final Pattern outer = Pattern.compile("\\\"[^\\\"]*\\\""); 

private String replaceCommasInsideQuotes(String s) { 
    StringBuffer buff = new StringBuffer(); 
    Matcher m = outer.matcher(bdr); 
    while (m.find()) { 
     m.appendReplacement(buff, ""); 
     buff.append(m.group().replaceAll(",", "#")); 
    } 
    m.appendTail(buff); 
    return buff.toString(); 
} 
관련 문제