gpt4 book ai didi

Java 等价于 PHP 的 preg_replace_callback

转载 作者:IT老高 更新时间:2023-10-28 20:57:06 27 4
gpt4 key购买 nike

我正在将应用程序从 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 中执行此操作的理想方法是什么?

最佳答案

当您可以在循环中使用 appendReplacement() 和 appendTail() 时,尝试模拟 PHP 的回调功能似乎需要做很多工作:

StringBuffer resultString = new StringBuffer();
Pattern regex = Pattern.compile("regex");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
// You can vary the replacement text for each match on-the-fly
regexMatcher.appendReplacement(resultString, "replacement");
}
regexMatcher.appendTail(resultString);

关于Java 等价于 PHP 的 preg_replace_callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/375420/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com