Use regex to replace sequences in a string with modified characters
java, regex, replace, string
Solution
This works:
while(str.matches(".*(.)\\1.*")) {
str = str.replaceAll("(.)\\1", "$1*$1");
}
return str;
Explanation of the regex:
The search regex `(.)\\1`:
- `(.)` means "any character" (the `.`) and the brackets create a group - group 1 (the first left bracket)
- `\\1`, which in regex is `\1` (a java literal `String` must escape a backslash with another backslash) means "the first group" - this kind of term is called a "back reference"
So together `(.)\1` means "any repeated character"
The replacement regex `$1*$1`:
- The `$1` term means "the content captured as group 1"
Recursive solution:
Technically, the solution called for on that site is a recursive solution, so here is recursive implementation:
public String pairStar(String str) {
if (!str.matches(".*(.)\\1.*")) return str;
return pairStar(str.replaceAll("(.)\\1", "$1*$1"));
}
Problem
I am trying to solve a codingbat problem using regular expressions whether it works on the website or not. So far, I have the following code which does not add a `*` between the two consecutive equal characters. Instead, it just bulldozes over them and replaces them with a set string. ``` public String pairStar(String str) { Pattern pattern = Pattern.compile("([a-z])\\1", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(str); if(matcher.find()) matcher.replaceAll(str);//this is where I don't know what to do return str; } ``` I want to know how I could keep using regex and replace the whole string. If needed, I think a recursive system could help.