Madhusudan
Madhusudan

Reputation: 4815

Java - Remove spaces around comma outside quoted String?

I have a String as shown below:

String s = "A,  Category,   \"Agriculture, forestry and fishing\",";

I want to remove spaces around comma (which are outside quotes). So my string should look like:

A,Category,"Agriculture, forestry and fishing",

I tried following RE:

String s = s.replaceAll("[,]\\s+", ",");

but output is:

A,Category,"Agriculture,forestry and fishing",

What changes should I do in my regular expression to avoid changes for commas inside quotes?

Upvotes: 2

Views: 3363

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

You can use this :

String str = "A,  Category,   \"Agriculture, forestry and fishing\",";
String result = str.replaceAll(" (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", "");
//------------------------------^--------------------------------------
System.out.println(result);

This will print :

A,Category,"Agriculture, forestry and fishing",
//----------------------^---------------------

The space inside the quotes is not changes, just outside the quotes.


Here is a code DEMO and here is a regex DEMO


EDIT

This part is from @Exception_al so he suggest to use this :

String result = str.replaceAll("(\\s*,\\s*)(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", ",");

This solution is very good if you want to replace all spaces between comma , and the word.

You can check how this can work in regex DEMO

Upvotes: 2

Related Questions