有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在同一个句子中分别替换同一个单词但大小写不同?

例如,替换“如何使用Matcher替换同一句子中的不同方式?”用“LOL,我是否在同一句话中替换不同的LOL?”

如果所有的大写字母都是“HOW is all caps”,则将其替换为LOL。否则,将其替换为LOL

我只知道如何找到它们:

String source = "HOW do I replace different how in the same " +
                "sentence by using Matcher?"

Pattern pattern = Pattern.compile(how, Pattern.CASE_INSENSITIVE);
    Matcher m = pattern.matcher(source);
    while (m.find()) {
         if(m.group.match("^[A-Z]*$"))        
              System.out.println("I am uppercase");
         else
              System.out.println("I am lowercase");

    }

但我不知道如何使用matcher和pattern来替换它们


共 (2) 个答案

  1. # 1 楼答案

    这里有一种方法可以实现你的目标:(不一定是最有效的,但它是有效的,而且简单易懂)

    String source = "HOW do I replace different how in the same sentence by using Matcher?";
        String[] split = source.replaceAll("HOW", "LOL").split(" ");
        String newSource = "";
        for(int i = 0; i < split.length; i++) {
            String at = split[i];
            if(at.equalsIgnoreCase("how"))  at = "lol";
            newSource+= " " + at;
        }
        newSource.substring(1, newSource.length());
    //The output string is newSource
    

    替换所有大写字母,然后重复每个单词,并将剩余的“how”替换为“lol”。末尾的子字符串只是为了删除额外的空间

  2. # 2 楼答案

    我想出了一个非常愚蠢的解决方案:

    String result = source;
    result = result.replaceAll(old_Word, new_Word);
    result = result.replaceAll(old_Word.toUpperCase(), 
    newWord.toUpperCase());