简体   繁体   中英

Why is this Regex not removing all 3 or more occurrences from a String?

Having a little trouble with this regex. I'm trying to take an input and remove all 3 or more occurrences of a letter.

Code

String input = "hhheeeelllooo";
System.out.println(input.replaceAll("(.)\\1{3,}", "$1"));

Actual Output

hhhelllooo

Expected Output

hheelloo

Your pattern doesn't match 3 or more occurrences: it matches 4 or more occurrences - the first occurrence, and the 3 or more following occurences of the same character.

Change the {3,} to {2,} if you want it to match 3 or more, and change the $1 to $1$1 to keep the first two occurrences in the output.

Ideone demo

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