正则表达式替换所有逗号,除了用双引号java括起来

时间:2014-03-31 06:40:52

标签: java regex

我想使用regex替换除java中的双引号之外的所有逗号。我将输出除外\"Lee Rounded Neck, Printed\"#410.00#300.00#\"Red Blue\"#lee"

String line="\"Lee Rounded Neck, Printed\" 410.00 300.00,\"Red Blue\",lee";
    String repl = line.replaceAll("(?!\")\\,", "#");
    System.out.println("Replaced => " + repl);

但我得到了"Lee Rounded Neck# Printed" 410.00 300.00#"Red Blue"#lee

请有人在这方面帮助我

2 个答案:

答案 0 :(得分:2)

试试,

line.replaceAll(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", "#");

enter image description here

答案 1 :(得分:1)

没有正则表达式:

String line="\"Lee Rounded Neck, Printed\" 410.00 300.00,\"Red Blue\",lee";
System.out.println(line);

char[] line2 = line.toCharArray();
boolean insideQuotes = false;
for (int i = 0; i < line.length(); ++i) {
  if (line.charAt(i) == '\"')
    insideQuotes = !insideQuotes;
  else if (line.charAt(i) == ',' && !insideQuotes)
    line2[i] = '#';
}
line = String.valueOf(line2);
System.out.println(line);

输出:

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

Ideone