I have used many Regex to do this, but the problem is i want to consider also:
abc- -abc //should output abc-abc
abc -- abc //should output abc - abc
abc- - abc //should output abc- abc
abc - -abc //should output abc -abc
I have used:
String x=x.replaceAll("[\\-*]{2,}","-");
You can use the following regular expression:
-(\\s*-)+
-
: matches -
literally.(...)+
: grouping (1+ times)\\s*-
: matches -
optionally space (\s
) prependedx = x.replaceAll("-(\\s*-)+", "-");