Regex to replace repeated characters

java regex

2656 просмотра

2 ответа

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"


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

Автор: Rajith Shanika Источник Размещён: 12.11.2019 09:27

Ответы (2)

5 плюса


Change your regex like below.

  • ( 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.


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

1 плюс

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
Вопросы из категории :