开发者

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 ca开发者_如何学JAVAptured group in upper case?


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜