Regex to replace repeated characters
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"
replaceAll("(.)\\1+","$1"))
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.
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.
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
.
Вопросы из категории :
- java В чем разница между int и Integer в Java и C #?
- java Как я могу определить IP моего маршрутизатора / шлюза в Java?
- java Каков наилучший способ проверки XML-файла по сравнению с XSD-файлом?
- java Как округлить результат целочисленного деления?
- java Преобразование списка <Integer> в список <String>
- java Почему я не могу объявить статические методы в интерфейсе?
- java Библиотека Java SWIFT
- java Выключение компьютера
- java Как я могу воспроизвести звук на Java?
- java Когда выбирать отмеченные и непроверенные исключения
- regex Learning Regular Expressions
- regex Regex и unicode
- regex Мое регулярное выражение слишком подходит. Как мне это остановить?
- regex Как выполнить подстановку Perl для строки, сохранив оригинал?
- regex Замена n-го экземпляра совпадения с регулярным выражением в Javascript
- regex Как заменить простые URL ссылками?
- regex Python re.sub с флагом не заменяет все вхождения
- regex Как проверить адрес электронной почты в JavaScript
- regex Как экранировать текст для регулярного выражения в Java
- regex Регулярное выражение, которое будет соответствовать объявлению метода Java