Java正则表达式下划线

Java正则表达式下划线,java,regex,Java,Regex,我想替换给定字符串中的内容(左右双下划线,请参见代码),但无法使其正常工作。比如说: String test = "Hello! This is the content: __content__"; test.replaceAll("__content__", "Yeah!"); System.out.println("Output: " + test); 所以输出应该是:“输出:你好!这是内容:耶!” replaceAll的第一个参数中的正则表达式是错误的,但我不知道正确的那个。有人知道怎么

我想替换给定字符串中的内容(左右双下划线,请参见代码),但无法使其正常工作。比如说:

String test = "Hello! This is the content: __content__";
test.replaceAll("__content__", "Yeah!");
System.out.println("Output: " + test);
所以输出应该是:
“输出:你好!这是内容:耶!”

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中,字符串是不可变的,因此
replaceAll
不会修改字符串,而是返回一个新字符串。

它应该是:

String test = "Hello! This is the content: __content__";
test = test.replaceAll("__content__", "Yeah!");
System.out.println("Output: " + test);
返回结果字符串