Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex negative lookahead to replace non-triple characters

Tags:

java

regex

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?

like image 298
Help123 Avatar asked Oct 20 '22 05:10

Help123


1 Answers

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.

like image 66
Wiktor Stribiżew Avatar answered Oct 22 '22 00:10

Wiktor Stribiżew