Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing single commas but don't remove 3 adjacent commas in a sentence

Tags:

java

regex

In the below sentence:

String res = [what, ask, about, group, differences, , , or, differences, in, conditions, |? |]

I want to remove single commas (,) but don't want to remove three adjacent commas.

I tried with this regex: res.replaceAll("(,\\s)^[(,\\s){3}]", " ") but it is not working.

like image 746
Jayant Avatar asked Mar 15 '23 02:03

Jayant


1 Answers

An easy way to do that is by chaining two replaceAll invocations, instead of using only one pattern:

String input = 
"[what, ask, about, group, differences, , , or, differences, in, conditions, |? |]";

System.out.println(
    input
        // replaces
        //           | comma+space not preceded/followed by other comma
        //           |                 | with space
        .replaceAll("(?<!, ), (?!,)", " ")
        // replaces
        //           | 3 consecutive comma+spaces
        //           |          | with single comma+space
        .replaceAll("(, ){3}", ", ")
);

Output

[what ask about group differences, or differences in conditions |? |]
like image 190
Mena Avatar answered Apr 08 '23 21:04

Mena