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
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
using a regex:
var myString='123345'
myString.replace(/([0-9])\1/g,'$1')
that will match exactly 2 repeats.
'123334'.replace(/([0-9])\1+/g,'$1')
Probably a replaceAll("(\\d)\\1+", "$1")
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"));
This is a regular expression mathing two repeating digits (x being the digit)
[x]{2}(?!=[x])
I finally did it myself. Those who are looking for the solution, this is how I did it:
import java.util.regex.*;
public class RepetingDigits{
public static void main(String[] args) {
String word = "77433211";
Pattern pattern = Pattern.compile("(\\d)\\1");
Matcher matcher = pattern.matcher(word);
word = matcher.replaceAll("$1");
System.out.println(word);
}
}
Even simpler:
**word = word.replaceAll("(\\d)\\1", "$1");**