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.
This works:
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 literalStringmust escape a backslash with another backslash) means “the first group” – this kind of term is called a “back reference”So together
(.)\1means “any repeated character”The replacement regex
$1*$1:$1term 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: