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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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)\\1would only replace them by pair:777xx=>77xx(thank you Ben Doom for the remark)So:
will return
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 expressionWarning:
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.