How to find two adjacent repeating digits and replace them with a single digit in Java?

I need to find two adjacent repeating digits in a string and replace with a single one. How to do this in Java. Some examples:

123345 should be 12345 77433211 should be 74321


Probably a replaceAll("(\d)\1+", "$1")

  • $ plays a special role in a replacing string, designating the first capturing group.
  • + allows for replacing as many identical number as possible (\d)\1 would only replace them by pair: 777xx => 77xx (thank you Ben Doom for the remark)


System.out.println("77433211".replaceAll("(\d)\1+", "$1"));

will return


String java.lang.String.replaceAll(String regex, String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement.

An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression


Warning: String.replaceAll() function does not modify the String on which it is applied. It returns a modified String (or a new String with the same content if the pattern does not match anything)

So you need to affect the result of a replaceAll() call to itself to actually update your String with the regexp changes.

String aString = "77433211"
aString = aString.replaceAll("(\d)\1+", "$1"));

Leave a Reply

Your email address will not be published. Required fields are marked *