美文网首页
Java----Pattern与Matcher使用实例

Java----Pattern与Matcher使用实例

作者: 不过意局bugyj | 来源:发表于2018-09-06 23:13 被阅读0次

    参考大神的博客:https://blog.csdn.net/zengxiantao1994/article/details/77803960

    Pattern的创建:

    Pattern的构造器被保护了起来,创建Pattern对象要靠使用compile方法编译正则表达式的返回Pattern的对象实例来实现!
    两种compile方法:

    public class testCompileMethodInPattern {
        public static void main(String[] args) {
            String regex = "[1-9]\\d*.+[1-9]\\d*=?";
            Pattern pattern = Pattern.compile(regex);
            System.out.println(pattern.pattern());
            System.out.println(pattern.flags());
        }
    }
    
    运行结果

    使用pattern.pattern()获取编译的正则表达式,而flags()获得的是使用compile(String regex,int falg)创建Pattern对象时设置的!flag是用来控制正则表达式匹配行为的,默认值为0!

    Pattern有几个内置的flag类型及作用:

    名字 作用 十六进制值
    Pattern.CANON_EQ 启用规范等价。当且仅当两个字符的“正规分解(canonicaldecomposition)”都完全相同的情况下,才认定匹配。默认情况下,不考虑“规范相等性(canonical equivalence)”。 0x80
    Pattern.CASE_INSENSITIVE 启用不区分大小写的匹配。默认情况下,大小写不敏感的匹配只适用于US-ASCII字符集。这个标志能让表达式忽略大小写进行匹配,要想对Unicode字符进行大小不敏感的匹配,只要将UNICODE_CASE与这个标志合起来就行了。 0x02
    Pattern.COMMENTS 模式中允许空白和注释。在这种模式下,匹配时会忽略(正则表达式里的)空格字符(不是指表达式里的“\s”,而是指表达式里的空格,tab,回车之类)。注释从#开始,一直到这行结束。可以通过嵌入式的标志来启用Unix行模式。 0x04
    Pattern.DOTALL 启用dotall模式。在这种模式下,表达式‘.’可以匹配任意字符,包括表示一行的结束符。默认情况下,表达式‘.’不匹配行的结束符。 0x20
    Pattern.LITERAL 启用模式的字面值解析。 0x10
    Pattern.MULTILINE 启用多行模式。在这种模式下,‘^’和‘’分别匹配一行的开始和结束。此外,‘^’仍然匹配字符串的开始,‘’也匹配字符串的结束。默认情况下,这两个表达式仅仅匹配字符串的开始和结束。 0x08
    Pattern.UNICODE_CASE 启用Unicode感知的大小写折叠。在这个模式下,如果你还启用了CASE_INSENSITIVE标志,那么它会对Unicode字符进行大小写不敏感的匹配。默认情况下,大小写不敏感的匹配只适用于US-ASCII字符集。 0x40
    Pattern.UNIX_LINES 启用Unix行模式。在这个模式下,只有‘\n’才被认作一行的中止,并且与‘.’、‘^’、以及‘$’进行匹配。 0x01

    Pattern之使用split进行字符串分割

    使用Pattern对象编译的正则表达式所匹配的子字符串对字符串进行分割:

    public class testSplitMethodInPattern {
        public static void main(String[] args) {
            String regex = "[+\\-*/]";
            Pattern pattern = Pattern.compile(regex);
            String []nums = pattern.split("13+29-44*55/22");
            for (String num : nums) {
                System.out.print(num + " ");
            }
        }
    }
    
    运行结果

    将split方法改成:

    String []nums = pattern.split("13+29-44*55/22", 2);
    
    运行结果

    即后面的整数类型入参觉得的是字符串被分割后的段数

    Pattern使用matchs进行字符串的全匹配

    pattern的matches方法对字符串进行一次匹配,只有全部符合规则才能返回true!

    public class testMatchesMethodInPattern {
        public static void main(String[] args) {
            String regex = "[1-9]\\d*[+\\-*/][1-9]\\d*=?";
            System.out.println(Pattern.matches(regex, "2315+5555="));
            System.out.println(Pattern.matches(regex, "123456*4556"));
            System.out.println(Pattern.matches(regex, "0112897+440="));
            System.out.println(Pattern.matches(regex, "22+023"));
        }
    }
    
    运行结果

    Pattern的matcher(CharSequence input)方法

    该方法返回的是一个Matcher对象,Matcher类的构造方法也被peivate保护了起来,只能使用这个方法创建,Pattern类只能做一些简单的匹配操作,要想得到更强更便捷的正则匹配操作,那就需要将Pattern与Matcher一起合作。Matcher类提供了对正则表达式的分组支持,以及对正则表达式的多次匹配支持。

    public class testMatcherMethodInPattern {
        public static void main(String[] args) {
            String regex = "[1-9]\\d*[+\\-*/][1-9]\\d*=?";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher("1+2");
            System.out.println(matcher.pattern());
        }
    }
    
    运行结果

    可以看出Matcher的pattern的方法也是显示生成自己的pattern编译的正则表达式!

    Matcher类方法详解:

    matches(String content)

    和Pattern的matches方法一样,不赘述

    lookAt()方法

    与字符串的前缀匹配。

    public class testCompileMethodInPattern {
        public static void main(String[] args) {
            String regex = "[1-9]\\d*[+\\-*/][1-9]\\d*=?";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher("1+2dasfdsadfeeesdfxca");
            System.out.println(matcher.lookingAt());
            matcher = pattern.matcher("a1+2asdfasdfsadf");
            System.out.println(matcher.lookingAt());
        }
    }
    
    运行结果

    find()方法

    在字符串中找是否有匹配的子字符串,有则返回ture

    public class testCompileMethodInPattern {
        public static void main(String[] args) {
            String regex = "[1-9]\\d*[+\\-*/][1-9]\\d*=?";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher("asdfasd11+2dasfdsadfeeesdfxca");
            System.out.println(matcher.find());
            matcher = pattern.matcher("asdfasd12dasfdsadfeeesdfxca");
            System.out.println(matcher.find());
            matcher = pattern.matcher("1+1");
            System.out.println(matcher.find());
        }
    }
    
    运行结果

    start()和end()方法

    前者是返回匹配到的字符串的第一个字符在字符串中的索引,后者则返回最后一个的索引+1

    public class testCompileMethodInPattern {
        public static void main(String[] args) {
            String regex = "[1-9]\\d*[+\\-*/][1-9]\\d*=?";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher("a11+2dasfdsadfeeesdfxca");
            if (matcher.find()) {
                System.out.println("The index of the final one character is " + matcher.start());
                System.out.println("The index of the last one character is " + matcher.end());
                System.out.println("The content of the corresponding substring of this string is " + matcher.group());
            }
        }
    }
    
    运行结果

    只有有匹配的子字符串的情况时才可以调用者几个方法,否则报错!

    对匹配到的字符串进行分割操作

    在正则表达式中使用括号对想要分割的方式进行添加!
    举例:

    public class testCompileMethodInPattern {
        public static void main(String[] args) {
            String regex = "([1-9]\\d*)([+\\-*/])([1-9]\\d*=?)";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher("a11+2dasfdsadfeeesdfxca");
    
            System.out.println(matcher.find());
    
            System.out.println(matcher.groupCount());
    
            for (int i = 0; i <= matcher.groupCount(); i++) {
                System.out.println("The index of the final one character is " + matcher.start(i));
                System.out.println("The index of the last one character is " + matcher.end(i));
                System.out.println("The content of the corresponding substring of this string is " + matcher.group(i));
            }
        }
    }
    

    注意对正则表达式的分割

    运行结果

    由图片可以看出,matcher中的group第一个显示的是匹配到的字符串及其信息后面才是我们分割的结果!

    一个字符串有多个匹配的子字符串的情况

    如果有多个匹配到的字符串,多用几次find就可以了!find方法第一次调用只匹配字符串中第一个匹配到的字符串,再调一次匹配第二个,以此类推!
    如在上面一段代码稍稍修改下:

    public class testFindMethodInPattern {
        public static void main(String[] args) {
            String regex = "([1-9]\\d*)([+\\-*/])([1-9]\\d*=?)";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher("a11+2dasfdsa11+22esdfxca");
    
            System.out.println(matcher.find());
            matcher.find();
    
            System.out.println(matcher.groupCount());
    
            for (int i = 0; i <= matcher.groupCount(); i++) {
                System.out.println("The index of the final one character is " + matcher.start(i));
                System.out.println("The index of the last one character is " + matcher.end(i));
                System.out.println("The content of the corresponding substring of this string is " + matcher.group(i));
            }
        }
    }
    
    运行结果

    看!多调用一次find方法就匹配到第二段字符串了!

    或者还可以在find方法中添加一个开始匹配的索引值,正则表达式只匹配这个整形参数索引后面的子字符串:

    matcher.find(12)
    

    效果和使用两次find的一样!

    相关文章

      网友评论

          本文标题:Java----Pattern与Matcher使用实例

          本文链接:https://www.haomeiwen.com/subject/evsfgftx.html