Java去掉字符串中的特殊符号只保留中文数字和字母

今天在做一个导入功能发现用户导入的数据有特殊符号,于是想着给他去掉,搜了一下发现大多数方法都只保留了字母数字,连中文都去掉了,这很明显不符合我的需求

直接上代码

/**
 * @author Sakura
 * @date 2024/8/27 15:18
 */
public class StringUtil {

    public static String replaceSpecialCharacter(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        // Replace all non-alphanumeric, non-Chinese characters (except spaces) with an empty string
        return input.replaceAll("[^a-zA-Z0-9\\s\\u4e00-\\u9fa5]", "");
    }


    public static void main(String[] args) {
        String input = "Hello,/ 世界! @2024#";
        String result = replaceSpecialCharacter(input);
        System.out.println(result);  // Output: Hello 世界 2024
    }
}

运行一下

在这里插入图片描述

可以发现特殊符号没了但是还有空格
改进一下

/**
 * @author Sakura
 * @date 2024/8/27 15:18
 */
public class StringUtil {

    public static String replaceSpecialCharacter(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        // Replace all non-alphanumeric, non-Chinese characters (including spaces) with an empty string
        return input.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]", "");
    }

    public static void main(String[] args) {
        String input = "Hello,/ 世界! @2024#";
        String result = replaceSpecialCharacter(input);
        System.out.println(result);  // Output: Hello世界2024
    }
}

再运行一下

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子非衣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值