【问题标题】:How do I replace the same word but different case in the same sentence separately?如何在同一个句子中分别替​​换相同的单词但不同的大小写?
【发布时间】:2017-05-13 23:47:15
【问题描述】:

例如,替换“如何使用 Matcher 在同一个句子中替换不同的方式?”用“大声笑我要在同一个句子中替换不同的大声笑吗?”

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

    }

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

【问题讨论】:

  • 最好的方法是不要使用正则表达式。
  • 您能发布您的解决方案吗?因为我认为使用正则表达式来做到这一点有点低效......
  • 嗯...我的解决方案?很抱歉,这是一个问答网站,而不是“请免费编写代码”网站。
  • 好的,谢谢:)

标签: java regex pattern-matching matcher


【解决方案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】:

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

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

【讨论】:

    猜你喜欢
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多