相关疑难解决方法(0)

Java相当于PHP的preg_replace_callback

我正在将应用程序从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中这样做的理想方法是什么?

php java regex preg-replace

33
推荐指数
2
解决办法
7312
查看次数

将字符串中的所有实例替换为唯一替换

我试图用唯一的替换来替换特定字符串的所有实例。

我想要什么:

如果我有这个字符串:

String testScript = "while(true) { } while   (10 < 7) { } while((10 < 7)) { }";
Run Code Online (Sandbox Code Playgroud)

我想要这个输出:

while(arg0 < 5000 && true) { } while(arg1 < 5000 && 10 < 7) { } while(arg2 < 5000 && (10 < 7)) { }
Run Code Online (Sandbox Code Playgroud)

我拥有的:

但是,传入的字符串replaceAll不会再次被查询(现在我想起来很明显)。

while(arg0 < 5000 && true) { } while(arg0 < 5000 && 10 < 7) { } while(arg0 < 5000 && (10 < 7)){ }
Run Code Online (Sandbox Code Playgroud)

一如既往,我们非常感谢任何答案或评论。

SSCCE:

public static void main(String[] …
Run Code Online (Sandbox Code Playgroud)

java regex string

1
推荐指数
1
解决办法
652
查看次数

标签 统计

java ×2

regex ×2

php ×1

preg-replace ×1

string ×1