Java regex negative lookahead to replace non-triple characters

I am trying to take a number, convert it to a string and replace all characters that are not triple.

Eg. if I go to 1222331 , my replace method should return 222 . I can find that this template exists, but I need to get the value and save it in a string for additional logic. I do not want to do a for loop to iterate over this line.

I have the following code:

 String first = Integer.toString(num1); String x = first.replaceAll("^((?!([0-9])\\3{2})).*$",""); 

But it also replaces the triple digits. I only need this to replace the rest of the characters. Is my approach wrong?

+5
source share
1 answer

you can use

 first = first.replaceAll("((\\d)\\2{2})|\\d", "$1"); 

Watch the regex demo

The regular expression - ((\d)\2{2})|\d - matches either a digit that is repeated three times (and captures it in group 1), or simply matches any other digit. $1 simply restores the captured text in the resulting string, deleting all the rest.

+3
source

All Articles