有没有办法用修改后的捕获组内容替换正则表达式?
例:
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher(text);
resultString = regexMatcher.replaceAll("$1"); // *3 ??
Run Code Online (Sandbox Code Playgroud)
而且我想用$ 1替换所有出现次数乘以3.
编辑:
看起来,有些不对劲:(
如果我使用
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
String resultString = regexMatcher.replaceAll(regexMatcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
它抛出IllegalStateException:找不到匹配项
但
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
String resultString = regexMatcher.replaceAll("$1");
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
工作正常,但我不能改变$ 1 :(
编辑:
现在,它的工作:)
我正在将应用程序从PHP迁移到Java,并且在代码中大量使用正则表达式.我在PHP中遇到过似乎没有java等价物的东西:
preg_replace_callback()
Run Code Online (Sandbox Code Playgroud)
对于正则表达式中的每个匹配,它调用一个函数,该函数将匹配文本作为参数传递.作为示例用法:
$articleText = preg_replace_callback("/\[thumb(\d+)\]/",'thumbReplace', $articleText);
# ...
function thumbReplace($matches) {
global $photos;
return "<img src=\"thumbs/" . $photos[$matches[1]] . "\">";
}
Run Code Online (Sandbox Code Playgroud)
在Java中这样做的理想方法是什么?
我正在寻找一种非常简单的方法来获得类似以下JavaScript代码的东西.也就是说,对于每个匹配,我想调用某个转换函数并将结果用作替换值.
var res = "Hello World!".replace(/\S+/, function (word) {
// Since this function represents a transformation,
// replacing literal strings (as with replaceAll) are not a viable solution.
return "" + word.length;
})
// res => "5 6"
Run Code Online (Sandbox Code Playgroud)
只有..在Java中.并且,优选地作为可以重复使用的"单一方法"或"模板".