4

I need to remove all redundant hyphens in a given string, e.g.: "Bla----Bla---Bla--Bla" to "Bla-Bla-Bla-Bla", using as little code as possible.

At the moment I've implemented this:

url = url.replace('----', '-');
url = url.replace('---', '-');
url = url.replace('--', '-');

to achieve this.

Is there a way to use the String.replaceAll method to achieve this?

Thank You!

1 Answer 1

6

You could use replaceAll with a regular expression as follows:

url = url.replaceAll('-+','-');

This says "match one or more (+) hyphens (-)" and we replace it with the singular hyphen (-).

2
  • An alternative would be '-{2,}, which specifies that any number of hyphens >= 2 get matched by the regex. Using '-+' is shorter, using {x,y} allows you to be more specific (x or more when y is left blank, between x and y instances when x and y are given)
    – Derek F
    Sep 23, 2020 at 15:51
  • Cool! It worked as expected! Thank you!
    – jdrees
    Sep 23, 2020 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.