正则表达式用于替换整个单词,而不是字符。

huangapple go评论63阅读模式
英文:

regex to replace a whole word, not characters

问题

我有以下代码片段:

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

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

示例:

Dean and James -> Dean James

Deand James -> Deand James

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

这行代码应如何修改?

s = s.replaceAll("(?i)\\b" + str + "\\b(\\s+)?", "");
英文:

i have the following snippet:

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

I need to alter the regex in it, so as to replace the "and" or "the" found in a string as a word, not as just part of a word.

example:

Dean and James -> Dean James

Deand James -> Deand James

I also need to keep the case insensitive replacement,

how this line should become?

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

答案1

得分: 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(" +", " ");

输出结果:Deand James

英文:

You need to use \b(word boundary) to replace the whole word only and after replace all multiple spaces with a single space.

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

Output: Deand James

答案2

得分: 0

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

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

The first part is quite easy: You don't want to replace "and" with "" but rather " and " (a full word defined by being surrounded with spaces) with " ", so something similar to

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

huangapple
  • 本文由 发表于 2020年10月6日 19:08:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64224573.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定