Dónal
Dónal

Reputation: 187499

replace all captured groups

I need to transform something like: "foo_bar_baz_2" to "fooBarBaz2"

I'm trying to use this Pattern:

Pattern pattern = Pattern.compile("_([a-z])");
Matcher matcher = pattern.matcher("foo_bar_baz_2");

Is it possible to use matcher to replace the first captured group (the letter after the '_') with the captured group in upper case?

Upvotes: 0

Views: 1245

Answers (3)

wjans
wjans

Reputation: 10115

You can use appendReplacement/appendTail methods of the matcher like this:

Pattern pattern = Pattern.compile("_([a-z0-9])");
Matcher matcher = pattern.matcher("foo_bar_baz_2");

StringBuffer stringBuffer = new StringBuffer();
while(matcher.find()) {
    matcher.appendReplacement(stringBuffer, matcher.group(1).toUpperCase());
}
matcher.appendTail(stringBuffer);

System.out.println(stringBuffer.toString());

Upvotes: 3

Vlad
Vlad

Reputation: 10780

StringBuffer sb = new StringBuffer();
while (matcher.find()) {
    matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);

Upvotes: 1

Tomalak
Tomalak

Reputation: 338148

Yes. Replace with \U$1\E - represented as in Java string "\\U$1\\E"

As long as there is nothing else in your regex, you can dump the \E and shorten to \U$1.


Taking @TimPietzcker's comment into account, your regex itself should be "_([a-z0-9])".

Upvotes: 3

Related Questions