如何在同一个句子中分别替​​换相同的单词但不同的单词?

时间:2017-05-13 23:47:16

标签: java regex pattern-matching matcher

例如,替换"如何使用匹配器替换同一句子中的不同方式?"使用" LOL我可以在同一个句子中替换不同的lol吗?"

如果全部是大写,请将其替换为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");

    }

但我不知道如何使用匹配器和模式替换它们。

2 个答案:

答案 0 :(得分:2)

这是实现目标的一种方式:(不一定是最有效的,但它有效并且只是被理解)

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

替换全部大写,然后遍历每个单词并用&#34; lol&#34;替换剩余的&#34; how&#34; s。最后的子串只是删除额外的空间。

答案 1 :(得分:0)

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

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