Use Matcher#group() instead of $1
here
if (matcher.find()) {
System.out.println(matcher.replaceAll(matcher.group(1)
.toLowerCase()));
}
Lets you make use of toLowerCase()
then.
EDIT : (in response to OP's comments)
Matcher#group(n)
is same as $n
-- it refers to the n'th capture group. So, group(1)
and $1
both capture O
except that you can switch the capture toLowerCase()
.
The loop is being run by replaceAll()
not by the find()
. Matcher#find()
is required to initialize the groups, so that group(1)
returns the capture before replaceAll()
is invoked.
But, this also means the capture stays the same which suffices your requirements but would require the matcher to be reset for a string like BOobbOobboObbOoObbooOoOoOoOoOOb (notice the double b's). The loop would have to be driven by Mathcer#find()
now which means replaceAll()
gets traded with replaceFirst()
.
String regex = "([A-Za-z])\\1+";
String str = "BOobbOobboObbOoObbooOoOoOoOoOObb";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
str = matcher.replaceFirst(matcher.start() > 0 ? matcher.group(1)
.toLowerCase() : matcher.group(1));
matcher.reset(str);
}
System.out.println(str); // Bobobobobob
Matcher#start() is used here to identify if the match is at the start of input where case is left untouched.