java字符串去除空格、tab、回车等特殊字符

我们经常需要处理字符串中的一些特殊字符,这里记录使用正则表达式进行字符串中特殊字符的处理。

正则表达式中一些特殊字符的表示方式:

\\ 反斜杠
\t 空格 (’\u0009’)
\n 换行 (’\u000A’)
\r 回车 (’\u000D’)
\d 数字等价于[0-9]
\D 非数字等价于[^0-9]
\s 空白符号 [\t\n\x0B\f\r]ton
\S 非空白符号 [^\t\n\x0B\f\r]
\w 单独字符 [a-zA-Z_0-9]
\W 非单独字符 [^a-zA-Z_0-9]
\f 换页符
\e Escape

    /**
     * 去除字符串中的空格、回车、换行符、制表符等
     * @param str
     * @return
     */
    public static String removeSpecialChar(String str){
        String s = "";
        if(str != null){
        	// 定义含特殊字符的正则表达式
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            s = m.replaceAll("");
        }
        return s;
    }

原文链接:
https://blog.csdn.net/zhangzehai2234/article/details/53525598/

你可能感兴趣的:(学习笔记,Java)