Krešimir Čoko
Krešimir Čoko

Reputation: 115

Replace comma with a comma followed by space

Due to the way server-side data is formatted I need to reformat it with my own function and to prevent any unwanted reformatting I want to check if the string I'm reformatting needs to be reformatted.

Here is the condition and the regex involved.

String value = "test, test, test.";

if (!value.matches("/(\\s*, )/g")) {
    return value.replaceAll(",", ", ");
}
else {
    return value;
}

The expected result is if a string is: Test,test,test it will reformat it to Test, test, test.

The behavior I am getting is that even the value string in the code goes into the if condition when it should skip it and go into the else.

Edit after consulting with my reviewer

The best solution found here for me was ",(?! )", ", " but it solved a problem I didn't even have so I simplified it to ",(\\S)", ", $1".

The proposed solution would add a after , even if the , would be at the end of the string which is something I didn't want.

Also in my question, I had a redundant if condition which I removed and simplified the solution to:

String value = "Test,test,test";

return value.replaceAll(",(\\S)", ", $1");

Output:

Test, test, test

Upvotes: 0

Views: 2164

Answers (2)

Pedro Lobito
Pedro Lobito

Reputation: 99031

You can use:

result = subject.replaceAll(",([^ ])", ", $1");

enter image description here


Demo

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

You don't need to check, you can just use :

value = value.replaceAll("\\s*,\\s*", ", ");

Input for example :

test ,   test, test.

Output

test, test, test.

Upvotes: 2

Related Questions