replace all captured groups

二次信任 提交于 2019-12-11 20:01:09

问题


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


来源:https://stackoverflow.com/questions/6761658/replace-all-captured-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!