replace all captured groups

2019-09-04 16:47发布

问题:

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?

回答1:

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());


回答2:

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])".



回答3:

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