正则表达式

371 阅读2分钟

字符

  1. x : 表示任意字符,比如 a表示a
  2. \ 表示反斜线字符
  3. \r \n回车换行

字符类:把很多字符放在一起

  1. [abc] : 表示 a或者b或者c,不能同时匹配2个
  2. [^abc]: 表示任何字符都行,除了a 、b、c外
  3. [a-zA-Z] : 匹配a-z或者A-Z在内的所有字符
  4. [0-9]: 0-9的的字符[ ] 号默认就表示一个字符。
  5. '.' : 表示任何字符, 点字符本身 \.
  6. \d: 表示数字0-9 \d \D = [^0-9]
  7. \w: \w 表示单词字符 = [a-zA-Z_0-9]

字符边界匹配

  1. ^ : 以什么开头
  2. $ : 以什么结尾
  3. \b: 单词边界: 表示匹配的一个地方 就是不是单词字符(\w)之外的字符 hello world?lala 空格和?就是单词边界

数量词

  1. x? 表示x可以出现一次或0次
  2. x* 表示0次或多次
  3. x+ 表示至少一次或多次
  4. x{n}: 表示x恰好出现n次
  5. x{n,}: 表示x至少出现n次
  6. x{n,m}: 表示x至少n次但不能超过m次 ###Java中的使用

判断

  1. 判断邮箱是否合法
String regex = "\\w+@\\w{2,}(\\.\\w{2,3})+";
// \\w+ 一个或多个字符 @2个或多个字符 括号表示一个整体里的内容(点开头加2个或者3个字符)+1次或多次 
boolean flag = email.matches(regex);

分割字符串

        String str = "aa,bb,cc";
        String[] strs =  str.split(",");
        for (int i = 0; i < strs.length; i++) {
            System.out.println(strs[i]);
        }
        System.out.println("------------");

        str = "dd.ee.ff";
        strs =  str.split("\\.");
        for (int i = 0; i < strs.length; i++) {
            System.out.println(strs[i]);
        }
        System.out.println("------------");

        str = "gg  hh     jj";
        strs =  str.split("\\s+");
        for (int i = 0; i < strs.length; i++) {
            System.out.println(strs[i]);
        }
        System.out.println("------------");

        str = "E:\\JavaSE\\day14\\avi";
        strs =  str.split("\\\\");
        for (int i = 0; i < strs.length; i++) {
            System.out.println(strs[i]);
        } 
        System.out.println("------------");

通过正则替换字符串内容

        String phoneNumer = "133a517bzz";
        phoneNumer.replaceAll("[a-zA-Z]", "*");

Pattern 和 Matcher

  1. Matcher 可以通过对Pattern对象解释来匹配字符串,
  2. 可以把正则表达式编译为Pattern对象来匹配任意字符串
  3. 可以通过Patter获取Matcher来匹配获取字符串
        // 获取字符串中 4个 字符的单词
        String s = "Initializes a newly created {@code String} object so that it represents\n" +
                "     * an empty character sequence.  Note that use of this constructor is\n" +
                "     * unnecessary since Strings are immutable.";

        // \\b表示单词边界,也就是非字符的内容,表示 字符左右两边必须是非字符的内容,里面4个字符,组成单词
        Pattern pattern = Pattern.compile("\\b\\w{4}\\b");
        Matcher matcher = pattern.matcher(s);

        List<String>list = new ArrayList<>();
        while (matcher.find()) {
            list.add(matcher.group());
        }
        System.out.println(list);