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.
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 |? |]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With