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

如何用正则过滤特殊字符解决Java存DB名称字段报UncategorizedSQLException问题

异常根因

你遇到的1366字符串写入错误,是因为MySQL默认的utf8编码仅支持最大3字节的Unicode字符,而表情符号(如🎶)、特殊音符等属于4字节的utf8mb4字符,字段未配置utf8mb4编码时就会写入失败。

正则过滤实现(Java版)

下面两种方案可根据业务需求选择:

方案1:仅过滤导致报错的4字节特殊字符

适用于需要尽可能保留原有特殊字符,只剔除无法入库的4字节字符的场景:

import java.util.regex.Pattern;

public class DbStringFilter {
    // 匹配所有4字节UTF-8字符(覆盖表情、特殊符号等异常字符)
    private static final Pattern INVALID_4BYTE_CHAR = Pattern.compile("[\\x{1F000}-\\x{1FFFF}]");

    public static String filter4ByteChars(String input) {
        if (input == null || input.isBlank()) {
            return input;
        }
        return INVALID_4BYTE_CHAR.matcher(input).replaceAll("");
    }
}

说明:提前预编译Pattern可以避免每次调用都重新编译正则,提升性能

方案2:仅保留指定范围的合法字符

适用于对字段内容有明确格式要求,需要剔除所有非常规字符的场景:

import java.util.regex.Pattern;

public class DbStringFilter {
    // 匹配所有不在【中文、英文、数字、常见中英文标点】范围内的字符
    private static final Pattern INVALID_CHAR = Pattern.compile("[^a-zA-Z0-9\\u4E00-\\u9FA5,。、;:“”‘’()【】!@#¥%……&*()——+\\-=\\[\\]{};':\",./<>? ]");

    public static String filterInvalidChars(String input) {
        if (input == null || input.isBlank()) {
            return input;
        }
        return INVALID_CHAR.matcher(input).replaceAll("");
    }
}
额外建议
  • 若有权限修改数据库配置,优先将对应字段的字符集改为utf8mb4,无需过滤即可直接存储这类特殊字符,是成本最低的长期解决方案
  • 过滤逻辑中可以增加日志,记录原始字符串和过滤后的结果,方便后续业务数据问题排查

内容的提问来源于stack exchange,提问作者RookieCoder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 23:45:08