Maksim
Maksim

Reputation: 41

Java regex replaceAll

I need to remove \s*,\s* but only when it's not between ". For example, this string a, b , c, "a, b , , c," a ,, should look like abc"a, b , , c," a.

As I found out [^abc] means don't touch abc and \.* means everything so I tried this:

str = str.replaceAll("[^\"\\.*,\\.*\"]\\s*,\\s*", "");

Important: amount of " is even.

Upvotes: 2

Views: 97

Answers (1)

alpha bravo
alpha bravo

Reputation: 7948

Use this pattern

\s*,\s*(?=(?:(?:[^"]*"){2})*[^"]*$)  

Demo
and I guess in your case, replace \s with \\s

\s*,\s*                 # your pattern
(?=                     # look-ahead
    (?:(?:[^"]*"){2})*  # optional pairs of double quotes
    [^"]*$              # followed by optional anything but double quotes to the end
)  

Upvotes: 5

Related Questions