如何确保replaceAll将替换整个单词而不是subString

use*_*203 5 java regex replaceall

我有字典输入.迭代字典以替换key文本中的字典.但replaceAll功能也取代了subString.

如何确保它匹配整个单词(整体而不是一个subString)

String text= "Synthesis of 1-(2,6-dimethylbenzyl)-1H-indole-6-carboxylic acid [69-3] The titled compound (883 mg) sdvfshd[69-3]3456 as a white solid was prepared"

dictionary= {[69-3]=1-(2,6-dimethylbenzyl)-1H-indole-6-carboxylic acid }

for(Map.Entry<String, String> entry : dictionary.entrySet()){

        text=text.replaceAll("\\b"+Pattern.quote(entry.getKey())+"\\b", entry.getValue());

} 
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 7

replaceAll 将参数作为正则表达式.

在正则表达式,你必须字边界:\b(使用\\b在一个字符串).它们是确保您匹配单词而不是单词的一部分的最佳方式:"\\bword\\b"

但在你的情况下,你不能使用单词边界,因为你不是在寻找单词([69-3]不是单词).

我建议这个:

text=text.replaceAll("(?=\\W+|^)"+Pattern.quote("[69-3]")+"(?=\\W+|$)", ...
Run Code Online (Sandbox Code Playgroud)

我们的想法是匹配字符串结尾或不是单词的东西.我无法确保这对您来说是正确的解决方案:必须根据确切的完整用例调整此类模式.

请注意,如果您的所有键都遵循类似的模式,那么可能有一个比迭代字典更好的解决方案,例如,您可以使用类似的模式"(?=\\W+|^)\\[\\d+\\-\\d+\\](?=\\W+|$)".