You can use this code with a replacement in the find method:
String s = "[what, ask, about, group, differences, , , or, differences, in, conditions, |? |]"; StringBuffer result = new StringBuffer(); Matcher m = Pattern.compile("((?:\\s*,){3})|,").matcher(s); while (m.find()) { if (m.group(1) != null) { m.appendReplacement(result, ","); } else { m.appendReplacement(result, ""); } } m.appendTail(result); System.out.println(result.toString());
Watch the IDEONE demo
Exit: [what ask about group differences, or differences in conditions |? |] [what ask about group differences, or differences in conditions |? |]
The regular expression - ((?:\\s*,){3})|, - corresponds to 2 alternatives: either 3 commas separated by an optional space (which is fixed), or just a comma. If we get a hold, replace it with a comma. If the capture is zero, we match one comma, delete it.
source share