0

我想用java中双引号内的任何一个特殊字符(例如“#”)替换所有逗号。

下面是字符串:

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

输出 :

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

我试过这个:

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));
              }
          }
      }
}
}

使用上面的代码,我只能找到引号内出现的字符串的第一次出现,而不是第二次出现(“红色,蓝色”)。

4

3 回答 3

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:假设没有不平衡的双引号,也没有转义双引号的情况。

于 2013-08-15T18:11:57.010 回答
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());
于 2013-08-15T18:31:03.873 回答
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();
}
于 2013-08-15T19:37:56.357 回答