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
$plays a special role in a replacing string, designating the first capturing group.
+allows for replacing as many identical number as possible
(\d)\1would only replace them by pair:
77xx(thank you Ben Doom for the remark)
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
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"));