java 利用正则表达式去处字符串中的所有空格

转载自xcmercy的博客

目标

去除字符串中所有的空白字符,包括空格、制表符、回车符等所有空白字符

思路

根据字符串长度,利用循环遍历字符串此方法太笨拙。这里利用正则表达式,匹配所有的空白字符,然后将匹配到的空白字符替换为 “” 空串即可。

代码

private String replaceBlank(String s) {
    String result= null;
    if (s == null) {
        return result;
    } else {
        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(s);
        result= m.replaceAll("");
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37556444/article/details/85338448