Java如何将字符串中指定保留词大写且不影响其他含同字符的单词
独立保留词大写替换解决方案
问题原因
你当前使用的replaceAll()方法直接全局匹配所有和保留词相同的子串,没有判断该子串是否为独立单词,因此会误替换其他单词内部包含的相同字符段。
解决方案
使用正则表达式的单词边界匹配符\b,它会匹配单词字符(字母、数字、下划线)和非单词字符的交界位置,保证只有独立出现的保留词才会被替换。注意Java字符串中反斜杠需要转义,所以实际编写时要写成\\b。
修改后的实现代码
String value1 = "id often refers to identity, identification or backidarenx"; String value2 = "the base rate (usd) is a new busda for us [usd for yousdrs]"; applyCorrectCase(value1); applyCorrectCase(value2); String applyCorrectCase(String value) { String[] reservedWords = {"id", "usd"}; String newValue = value; for (String word : reservedWords) { // 拼接单词边界正则,仅匹配独立的保留词 String matchRegex = "\\b" + word + "\\b"; newValue = newValue.replaceAll(matchRegex, word.toUpperCase()); } System.out.println(newValue); return newValue; }
输出结果
运行上述代码后得到的输出和你预期的完全一致:
ID often refers to identity, identification or backidarenx the base rate (USD) is a new busda for us [USD for yousdrs]
内容的提问来源于stack exchange,提问作者Despotars
相关产品推荐
相关产品推荐

