英文:
Java String replace method with lambda funcion
问题
如果存在 "xyz",则调用 random 生成替换字符串。
英文:
I want do String replace without specifying replacement String as literal String.
Supplier<String> random = () -> anyExpensiveProcess();
String text = "abcd xyz";
text = text.replace("xyz", random);
If "xyz" exists, then call random to generate replacement String.
答案1
得分: 3
String.replace() 和 String.replaceAll() 函数不接受 lambda 表达式,但根据文档,"使用 str.replaceAll(regex, repl) 形式的此方法调用将产生与以下表达式完全相同的结果:
Pattern.compile(regex).matcher(str).replaceAll(repl)
因此,我建议您尝试以下方法:
Pattern.compile("xyz").matcher(text).replaceFirst(mr -> random.get());
编辑:Matcher 具有 replaceFirst 和 replaceAll,而不是 replace()。两者都接受 Function<MatchResult,String> replacer。
英文:
The String.replace() and String.replaceAll() functions do not accept a lambda but according to the docs, "an invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression:
Pattern.compile(regex).matcher(str).replaceAll(repl)
Therefore, I suggest you try:
Pattern.compile("xyz").matcher(text).replaceFirst(mr -> random.get());
Edit: Matcher has replaceFirst ond replaceAll, not replace().  Both take a Function<MatchResult,String> replacer.
答案2
得分: 1
你将需要自行创建方法:
public String replaceIfFound(String subject, String target, Supplier<String> replacement) {
    if (!subject.contains(target)) {
        return subject;
    }
    return subject.replace(target, replacement.get());
}
这样,只有当主体包含你要查找的字符串时,Supplier 才会被调用。
英文:
You will have to make your own method for that:
public String replaceIfFound(String subject, String target, Supplier<String> replacement) {
    if(!subject.contains(target)) {
      return subject;
    }
    return subject.replace(target, replacement.get())
}
This way the Supplier will only be invoked if the subject contains the String you're looking for.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论