You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 13:24:01