I'm trying to take a number, convert it into a string and replace all characters that are not a triple.
Eg. if I pass in 1222331
my replace method should return 222
. I can find that this pattern exists but I need to get the value and save it into a string for additional logic. I don't want to do a for loop to iterate through this string.
I have the following code:
String first = Integer.toString(num1);
String x = first.replaceAll("^((?!([0-9])\\3{2})).*$","");
But it's replacing the triple digits also. I only need it to replace the rest of the characters. Is my approach wrong?
You can use
first = first.replaceAll("((\\d)\\2{2})|\\d", "$1");
See regex demo
The regex - ((\d)\2{2})|\d
- matches either a digit that repeats thrice (and captures it into Group 1), or just matches any other digit. $1
just restores the captured text in the resulting string while removing all others.
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