【问题标题】:regex to replace a whole word, not characters正则表达式替换整个单词,而不是字符
【发布时间】:2020-10-06 19:39:36
【问题描述】:

我有以下sn-p:

String[] alsoReplace = {"and", "the", "&"};
    for (String str : alsoReplace) {
        s = s.replaceAll("(?i)" + str + "(\\s+)?" , "");
    }

我需要更改其中的正则表达式,以便将字符串中的“and”或“the”替换为单词,而不仅仅是单词的一部分。

示例:

迪恩和詹姆斯 -> 迪恩詹姆斯

迪安德詹姆斯 -> 迪安德詹姆斯

我还需要保持不区分大小写的替换,

这条线应该变成什么样子?

        s = s.replaceAll("(?i)" + str + "(\\s+)?" , "");

【问题讨论】:

  • 你不能使用string.replace(" and ", " "); 吗?或使用您的数组string.replace(" " + str + " ", " ");
  • @PhilippeB。替换单词是最后一个没有空格的单词。
  • 没错!感谢您指出这一点:)

标签: java regex


【解决方案1】:

您需要使用\b(单词边界)仅替换整个单词,然后将所有多个空格替换为一个空格。

String s = "Deand  and  James And";
String[] alsoReplace = {"and", "the", "&"};
for (String str : alsoReplace) {
    s = s.replaceAll("(?i)\\b" + str + "\\b" , "");
}
s = s.trim().replaceAll(" +", " "); // remove multiple space into single

输出:Deand James

【讨论】:

  • 我尝试过以下方法:s = s.replaceAll("\\b(?i)\\b" 我不知道为什么这是错误的
  • 你是否在正则表达式中添加了替换词?
  • 不用担心,我会使用你的建议,只是想知道为什么 "\\b(?i)\\b" 错误,谢谢
【解决方案2】:

第一部分非常简单:您不想将“and”替换为“”,而是将“and”(由空格包围的完整单词)替换为“”,因此类似于

String[] alsoReplace = {" and ", " the ", "&"};
for (String str : alsoReplace) {
  s = s.replaceAll("(?i)" + str + "(\\s+)?" , " ");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多