Java利用正則去除字符串中的空白字符

目標

去除字符串中全部的空白字符,包括空格、製表符、回車符等全部空白字符web

思路

根據字符串長度,利用循環遍歷字符串此方法太笨拙。這裏利用正則表達式,匹配全部的空白字符,而後將匹配到的空白字符替換爲 "" 空串便可。正則表達式

代碼

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(str);
        result= m.replaceAll("");
        return result;
    }
}