Java常用正则表达式

^相当于正则表达式里面的取反

匹配一个或多个数字:\\d+,[0-9]{1,}

匹配中文:[\u4e00-\u9fa5](unicode编码,是中文编码的开始和结束两个值)

匹配英文字母:[a-zA-Z]

 

1、匹配字符串里的数字

public static void main(String[] args) { 
       String regEx = "[^0-9]";
        String str1 = "abc123d456dfdAA;78';./";
        String str2 = "12345678";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher1 = pattern.matcher(str1);
        Matcher matcher2 = pattern.matcher(str2);
        String result1 = matcher1.replaceAll("").trim();
        String result2 = matcher2.replaceAll("").trim();
        System.out.println(result1);
        System.out.println(result2);
}

2、匹配中文

    public static void main(String[] args) {
        String str = "123大家好abc开心快乐ef每一天c";

        String reg = "[^\u4e00-\u9fa5]";

        Pattern pat = Pattern.compile(reg);

        Matcher mat=pat.matcher(str);

        String repickStr = mat.replaceAll("");

        System.out.println(repickStr);
    }

3、匹配英文 

    public static void main(String[] args) {
        String reg = "[^a-zA-Z]";
        String fileName = "TERMINAL_JOURNAL_DATA-20190506100000.txt ";
        String processType = fileName.replaceAll(reg, "");
        System.out.println(processType);//TERMINALJOURNALDATAtxt
    }

4、提取括号中的内容

    // 提取小括号里的值
    public static Pattern EXTRACT_PARENTHESES_PATTER = Pattern.compile("(?<=\\()[^\\)]+"); // 这个替换调响应的\\( 和\\),换成\\{, \\(, \\[ 等可以提取中括号,大括号里面的值,比较通用
    // 提取中括号里的值
    public static Pattern EXTRACT_MIDDLE_BRACKETS_PATTER = Pattern.compile("(\\[[^\\]]*\\])");


    public static void main(String[] args) {
        String str1 = "12,32(232,434),(大家好)";
        Matcher matcher = EXTRACT_PARENTHESES_PATTER.matcher(str1);
        List<String> parentheses = new ArrayList<>();
        while (matcher.find()){
            parentheses.add(matcher.group());
        }
        System.out.println("圆括号里面的值:" + parentheses.toString());
        //
        str1 = "12,32[232,434],[大家好]";
        matcher = EXTRACT_MIDDLE_BRACKETS_PATTER.matcher(str1);
        List<String> middleBrackets = new ArrayList<>();
        while (matcher.find()){
            middleBrackets.add(matcher.group());
        }
        System.out.println("中括号里面的值:" + parentheses.toString());
    }

 结果:

 

posted @ 2019-04-11 13:39  hy_wx  阅读(393)  评论(0编辑  收藏  举报