替换所有捕获的组 [英] replace all captured groups
本文介绍了替换所有捕获的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将以下内容转换为: foo_bar_baz_2
到 fooBarBaz2
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");
是否可以使用 matcher
进行替换捕获的组中的第一个捕获组( _后的字母)为大写字母?
Is it possible to use matcher
to replace the first captured group (the letter after the '_') with the captured group in upper case?
推荐答案
您可以使用appendReplacement匹配器的/ appendTail方法,如下所示:
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());
这篇关于替换所有捕获的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文