【问题标题】:How can I replace / edit only a specific word in Java?如何仅替换/编辑 Java 中的特定单词?
【发布时间】:2019-07-22 22:50:02
【问题描述】:

我想要替换/编辑一个特定的单词。但不幸的是,包含要替换的单词的其他单词也被替换了。

例子:

String test = "我是个工具";

现在如果我想用一些东西来代替“ool”这个词,“tool”也会被改变。那么我该如何解决这个问题呢?我只想编辑 ool 。 “工具”应该保持原样。

这里有一些代码:

public class StringMethoden {

public static void main(String[] args) {


    String bsp = "I am a ool tool";

    if (bsp.matches("(.*)ool(.*)")){


        bsp = bsp.replaceAll("ool", "test");
        System.out.println(bsp);
             }
    else {
        System.out.println("sentence does not conain 'ool' !");
    }}

输出:我是一个测试测试者

【问题讨论】:

  • 单词"ool"和部分单词"*ool*"有什么区别?完整的单词没有被其他字母包围。

标签: java string replace


【解决方案1】:

Java RegEx 中的单词边界 (\b) 确保字符串中的某个点是单词的开头/结尾。

bsp = bsp.replaceAll("\\bool\\b", "test");

【讨论】:

    【解决方案2】:

    这里有一个类似的问题处理方法,我们也可以通过以下方式使用.contains()方法,如果有问题可以随时提问。

        String bsp = "I am a ool tool";
        if (bsp.contains(" ool")) {
    
            bsp = bsp.replaceAll(" ool", " test");
            System.out.println(bsp);
        } else {
            System.out.println("sentence does not conain 'ool' !");
        }
    

    输出:

    我是测试工具

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      相关资源
      最近更新 更多