简体   繁体   中英

Java regex negative lookahead to replace non-triple characters

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM