0

I want to replace all commas except in double quotes in java using regex.I am excepting output as \"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);

But i am getting "Lee Rounded Neck# Printed" 410.00 300.00#"Red Blue"#lee

Please someone Help me in this regards

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
user3465603
  • 3
  • 1
  • 5
  • Here's how it would look in Perl: `s/((?:[^",]|"(?:[^"\\]|\\.)*")*),/$1#/g`. This also allows `"` to be escaped by a backslash inside a `"`-quoted string. `$1` refers to the first parenthesised expression; I expect there's a way to express this in Java. – j_random_hacker Mar 31 '14 at 06:50

2 Answers2

2

Try with,

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

enter image description here

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
1

Without regex:

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

Output:

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

Ideone

kol
  • 27,881
  • 12
  • 83
  • 120