我希望通过在检测到的组上调用函数来替换字符串中的某些模式.
更具体地说,我想举例来改造
String input = "normal <upper> normal <upper again> normal";
Run Code Online (Sandbox Code Playgroud)
成
String output = "normal UPPER normal UPPER AGAIN normal";
Run Code Online (Sandbox Code Playgroud)
正则表达式\<(.*?)\>"应该检测我想要转换的模式,但是使用
output = input.replaceAll("\\<(.*?)\\>", "$1".toUpperCase());
Run Code Online (Sandbox Code Playgroud)
不起作用,因为逻辑上它放在$1大写的情况下,也就是说,在方法中处理之前没有任何反应.
此外,我想要应用的方法是用替换字符串作为参数调用; 因此,"错误的天真方式"会更像
output = input.replaceAll("\\<(.*?)\\>", transform("$1"));
Run Code Online (Sandbox Code Playgroud)
你知道有什么诀窍吗?
习惯性的方法有点冗长:
Matcher m = Pattern.compile("\\<(.*?)\\>").matcher(input);
StringBuffer b = new StringBuffer();
while (m.find()) {
m.appendReplacement(b, transform(m.group());
}
m.appendTail(b);
output = b.toString();
Run Code Online (Sandbox Code Playgroud)