java替换功能

标签 java replace

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/

相关文章:

linux - 如何在linux命令中替换多个文件中的字符串

Java - 用正则表达式替换所有,然后替换第一次出现的字符串

Swift - 替换字符串的第二个字符

Python:替换字符串中的特定字符(重复问题)

java - 在设置可见之前向 JFrame 添加内容

java - 可以在同一应用程序内的 JComponent 之间的 DnD 中避免序列化吗?

java - Spring 缓存 - "Null key returned for cache operation"

Java进程: read stdout and stderr of a subprocess in a single thread

java - 在 xml 中使用 < 和 > 符号

mysql动态替换(就像搜索上的一个案例)