Java提取字符串中的汉字、字母、数字

1.提取汉字

public static void main(String[] args) {
        String str = " 我是123一段测abd试 空a格 的字符 串 ";
        System.out.println("过滤出汉字:" + str.replaceAll("\\s*","").replaceAll("[^(\\u4e00-\\u9fa5)]",""));
    }

 

 2.提取字母

public static void main(String[] args) {
        String str = " 我是123一段测abd试 空a格 的字符 串 ";
        System.out.println("过滤出字母:" + str.replaceAll("\\s*","").replaceAll("[^(A-Za-z)]",""));
    }

 

 3.提取数字

public static void main(String[] args) {
        String str = " 我是123一段测abd试 空a格 的字符 串 ";
        System.out.println("过滤出数字:" + str.replaceAll("\\s*","").replaceAll("[^(0-9)]",""));
    }

 

 4.提取数字+字母

public static void main(String[] args) {
        String str = " 我是123一段测abd试 空a格 的字符 串 ";
        System.out.println("过滤出数字+字母:" + str.replaceAll("\\s*","").replaceAll("[^(a-zA-Z0-9)]",""));
    }

5.过滤字符串空格

public static void main(String[] args) {
        String str1 = " 我是一段测试 空格 的字符 串 ";
        String str2 = " 我是一段测试 空格 的字符 串 ";
        String str3 = " 我是一段测试 \r空格 的字符 串 ";
        String str4 = " 我是一段测试 \r空格 的字符 串 ";
        String str5 = " 我是一段测试 \t空格 \r的字\n符 串 ";
        //去掉首尾空格
        System.out.println("去掉首尾空格:" + str1.trim());
        //去掉所有空格
        System.out.println("去掉所有空格:" + str2.replace(" ",""));
        System.out.println("去掉所有空格:" + str3.replaceAll(" ",""));
        System.out.println("去掉所有空格:" + str4.replaceAll(" +",""));
        //去掉特殊的空格、制表符、换页符
        System.out.println("去掉特殊的空格、制表符、换页符:" + str5.replaceAll("\\s*",""));
    }

posted @ 2020-08-13 15:16  缘故为何  阅读(10576)  评论(0编辑  收藏  举报