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)So:
System.out.println("77433211".replaceAll("(\\d)\\1+", "$1"));
will return
74321
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
java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With