Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正则表达式替换整个单词,而不是字符_Java_Regex - Fatal编程技术网

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

Java 正则表达式替换整个单词,而不是字符,java,regex,Java,Regex,我有以下片段: String[] alsoReplace = {"and", "the", "&"}; for (String str : alsoReplace) { s = s.replaceAll("(?i)" + str + "(\\s+)?" , ""); } 我需要修改其中的正则表达式,以便将字符串中的“and”或“the”

我有以下片段:

String[] alsoReplace = {"and", "the", "&"};
    for (String str : alsoReplace) {
        s = s.replaceAll("(?i)" + str + "(\\s+)?" , "");
    }
我需要修改其中的正则表达式,以便将字符串中的“and”或“the”替换为单词,而不仅仅是单词的一部分

例如:

迪安和詹姆斯->迪安·詹姆斯

迪恩德詹姆斯->迪恩德詹姆斯

我还需要保留不区分大小写的替换项

这条线应该变成什么样子

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

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

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

您需要使用
\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

输出:
deandjames

您不能使用
字符串。替换(“and”,”)?或者使用数组
字符串。替换(“+str+”,”)@PhilippeB。替换词是最后一个没有空格的词,对了!谢谢你指出:)我试过以下方法:s=s.replaceAll(“\\b(?i)\\b”我不知道为什么这是错误的你把replace单词放在正则表达式中了吗?不用担心,我会用你的建议,只是想知道,“\\b(?i)\\b”为什么会错,谢谢