Java String replace方法与lambda函数

huangapple go评论110阅读模式
英文:

Java String replace method with lambda funcion

问题

如果存在 "xyz",则调用 random 生成替换字符串。

英文:

I want do String replace without specifying replacement String as literal String.

  1. Supplier<String> random = () -> anyExpensiveProcess();
  2. String text = "abcd xyz";
  3. 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) 形式的此方法调用将产生与以下表达式完全相同的结果

  1. Pattern.compile(regex).matcher(str).replaceAll(repl)

因此,我建议您尝试以下方法:

  1. Pattern.compile("xyz").matcher(text).replaceFirst(mr -> random.get());

编辑:Matcher 具有 replaceFirstreplaceAll,而不是 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:

  1. Pattern.compile(regex).matcher(str).replaceAll(repl)

Therefore, I suggest you try:

  1. 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

你将需要自行创建方法:

  1. public String replaceIfFound(String subject, String target, Supplier<String> replacement) {
  2. if (!subject.contains(target)) {
  3. return subject;
  4. }
  5. return subject.replace(target, replacement.get());
  6. }

这样,只有当主体包含你要查找的字符串时,Supplier 才会被调用。

英文:

You will have to make your own method for that:

  1. public String replaceIfFound(String subject, String target, Supplier&lt;String&gt; replacement) {
  2. if(!subject.contains(target)) {
  3. return subject;
  4. }
  5. return subject.replace(target, replacement.get())
  6. }

This way the Supplier will only be invoked if the subject contains the String you're looking for.

huangapple
  • 本文由 发表于 2023年2月24日 01:35:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定