Java相当于PHP的preg_replace_callback

我正在将应用程序从PHP迁移到Java,并且在代码中大量使用了正则表达式。我遇到了PHP中似乎没有Java等效项的某些问题:


preg_replace_callback()

对于正则表达式中的每个匹配项,它都会调用一个函数,该函数将匹配文本作为参数传递给该函数。用法示例:


$articleText = preg_replace_callback("/\[thumb(\d+)\]/",'thumbReplace', $articleText);

# ...

function thumbReplace($matches) {

   global $photos;

   return "<img src=\"thumbs/" . $photos[$matches[1]] . "\">";

}

用Java做到这一点的理想方法是什么?


慕森卡
浏览 992回答 3
3回答

慕虎7371278

当您可以在循环中仅使用appendReplacement()和appendTail()时,尝试模拟PHP的回调功能似乎需要进行大量工作:StringBuffer resultString = new StringBuffer();Pattern regex = Pattern.compile("regex");Matcher regexMatcher = regex.matcher(subjectString);while (regexMatcher.find()) {&nbsp; // You can vary the replacement text for each match on-the-fly&nbsp; regexMatcher.appendReplacement(resultString, "replacement");}regexMatcher.appendTail(resultString);
打开App,查看更多内容
随时随地看视频慕课网APP