Regex to replace repeated characters

java regex

2656 просмотра

2 ответа

96 Репутация автора

Can someone give me a Java regex to replace the following.

If I have a word like this "Cooooool", I need to convert this to "Coool" with 3 o's. So that I can distinguish it with the normal word "cool".

Another ex: "happyyyyyy" should be "happyyy"

replaceAll("(.)\\1+","$1"))

I tried this but it removes all the repeating characters leaving only one.

Автор: Rajith Shanika Источник Размещён: 18.08.2015 11:24

Ответы (2)


5 плюса

148177 Репутация автора

Решение

Change your regex like below.

string.replaceAll("((.)\\2{2})\\2+","$1");
  • ( start of the first caturing group.
  • (.) captures any character. For this case, you may use [a-z]
  • \\2 refers the second capturing group. \\2{2} which must be repeated exactly two times.
  • ) End of first capturing group. So this would capture the first three repeating characters.
  • \\2+ repeats the second group one or more times.

DEMO

Автор: Avinash Raj Размещён: 18.08.2015 11:28

1 плюс

413 Репутация автора

I think you might want something like this:

str.replaceAll("([a-zA-Z])\\1\\1+", "$1$1$1");

This will match where a character is repeated 3 or more times and will replace it with the same character, three times.

$1 only matches one character, because you're surrounding the character to match.
\\1\\1+ matches the character only, if it occurs at least three times in a row.

This call is also a lot more readable, than having a huge regex and only using one $1.

Автор: G_hi3 Размещён: 18.08.2015 11:39
Вопросы из категории :
32x32