gpt4 book ai didi

Java 正则表达式下划线

转载 作者:行者123 更新时间:2023-11-30 06:14:12 24 4
gpt4 key购买 nike

我想替换给定字符串中的 content(左右双下划线,参见代码),但无法让它工作。所以像这样:

String test = "Hello! This is the content: __content__";
test.replaceAll("__content__", "Yeah!");
System.out.println("Output: " + test);

所以输出应该是:“Output: Hello! This is the content: Yeah!”replaceAll 的第一个参数中的正则表达式完全是错误的,但我不知道正确的那个。谁知道怎么做?

最佳答案

您忘记将 replaceAll 的返回值分配回原始字符串。 replaceAll(或任何其他字符串方法)不会更改原始字符串:

String test = "Hello! This is the content: __content__";
test = test.replaceAll("__content__", "Yeah!");
System.out.println("Output: " + test);

顺便说一句,你在这里甚至不需要正则表达式,只需使用replace:

test = test.replace("__content__", "Yeah!");

关于Java 正则表达式下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30644441/

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