Search code examples
javaregexstringreplaceall

Regex replace 2 or more dashes with one dash


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,}","-");

Solution

  • You can use the following regular expression:

    -(\\s*-)+
    
    • -: matches - literally.
    • (...)+: grouping (1+ times)
    • \\s*-: matches - optionally space (\s) prepended

    x = x.replaceAll("-(\\s*-)+", "-");