public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = "this is just just a text text";
System.out.println(s.replaceAll(" just ", " <b>just</b> "));
}
输出应该是 this is just just a text text,但我得到的是 this is just just a text text。有人可以帮助我理解这一点吗? 提前致谢!
最佳答案
做类似的事情:
System.out.println(s.replaceAll("just", "<b>just</b>"));
如果您只想替换 "just"
而不是任何以 "just"
开头的单词,则不适合。
否则输入如下:
String s = "this is justice just a text text";
将产生:
this is just ice just a text text
由于 replaceAll()
使用正则表达式,您可以通过期望 "just"
或 "just "
来处理空格。
通过这样做:
System.out.println(s.replaceAll("\\sjust|just\\s", "<b>just</b>"));
您将获得接近目标的结果,但输出中仍然存在一些空格问题(太多或不足),因为正则表达式会考虑之前或之后的空格并保持替换与您一致应保留输入中的空白。
更好的解决方案是调用两次 replaceAll()
:
System.out.println(s.replaceAll(" just ", " <b>just</b> ").replaceAll(" just ", " <b>just</b> "));
例如使用此输入:
String s = "this is a just just just adjusted justice test";
第一个 replaceAll()
每两个替换链式“just”一次:
this is a <b>just</b> just <b>just</b> adjusted justice test
this is a just just just adjusted justice test
对第一个 replaceAll()
返回的字符串调用的第二个 replaceAll()
会替换剩余的 "just "
:
this is a <b>just</b> <b>just</b> <b>just</b> adjusted justice test
this is a just just just adjusted justice test
它给出了准确的结果,但它不是最有效的方法,因为它解析了两倍的字符串。
更有效的解决方案可以使用模式
并定义一个不包含空格的组。通过这种方式,可以仅对 just
字符串执行替换。
关于java替换功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44181478/