使用java Regex将逗号替换为字符串中的任何特殊字符

时间:2013-08-15 17:46:01

标签: java regex

我想将所有逗号替换为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));
              }
          }
      }
}
}

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

3 个答案:

答案 0 :(得分: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:假设没有不平衡的双引号,并且没有双重报价转义的情况。

答案 1 :(得分: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());

答案 2 :(得分: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();
}