• 正则表达式 Pattern Matche find() matches() lookingAt()


    1 matces() lookingAt() find()区别
    • matches方法尝试将整个输入序列与该模式匹配。

    • lookingAt尝试将输入序列从头开始与该模式匹配。

    • find方法扫描输入序列以查找与该模式匹配的下一个子序列。  

     // matches()对整个字符串进行匹配,只有整个字符串都匹配了才返回true

            Pattern p=Pattern.compile("\d+");
            Matcher m=p.matcher("22bb23");
            m.matches();//返回false,因为bb不能被d+匹配,导致整个字符串匹配未成功.
            Matcher m2=p.matcher("2223");
            m2.matches();//返回true,因为d+匹配到了整个字符串
    
           // lookingAt()对前面的字符串进行匹配,只有匹配到的字符串在最前面才返回true
            Pattern p1=Pattern.compile("\d+");
            Matcher m3=p1.matcher("22bb23");
            m.lookingAt();//返回true,因为d+匹配到了前面的22
            Matcher m4=p1.matcher("aa2223");
            m2.lookingAt();//返回false,因为d+不能匹配前面的aa
    
           // find()对字符串进行匹配,匹配到的字符串可以在任何位置.
            Pattern p2=Pattern.compile("\d+");
            Matcher m5=p2.matcher("22bb23");
            m.find();//返回true
            Matcher m6=p2.matcher("aa2223");
            m2.find();//返回true
            Matcher m7=p2.matcher("aa2223bb");
            m3.find();//返回true
            Matcher m8=p2.matcher("aabb");
            m4.find();//返回false

    Pattern pattern = Pattern.compile(".*?o");
    Matcher matcher = pattern.matcher("zoboco");

    while(matcher.find()){
    System.out.println(matcher.group(0));
    }

    运行结果:

    zo
    bo
    co

    java 正则表达式中的分组

    正则表达式的分组在java中是怎么使用的. 
    start(),end(),group()均有一个重载方法它们是start(int i),end(int i),group(int i)专用于分组操作,Mathcer类还有一个groupCount()用于返回有多少组. 
    Java代码示例: 
    Pattern p=Pattern.compile("([a-z]+)(\d+)"); 匹配模式中一个括号就是一组
    Matcher m=p.matcher("aaa2223bb"); 
    m.find();   //匹配aaa2223 
    m.groupCount();   //返回2,因为有2组 
    m.start(1);   //返回0 返回第一组匹配到的子字符串在字符串中的索引号 
    m.start(2);   //返回3 
    m.end(1);   //返回3 返回第一组匹配到的子字符串的最后一个字符在字符串中的索引位置. 
    m.end(2);   //返回7 
    m.group();//返回aaa2223 m.group(1); //返回aaa,返回第一组匹配到的子字符串 m.group(2); //返回2223,返回第二组匹配到的子字符串

    参考链接  https://www.cnblogs.com/dgwblog/p/10073256.html

  • 相关阅读:
    IE6碰到的兼容问题小结
    Ueditor的asp版本,上传测试无问题
    localStorage存取json数据
    asp版 QQ登录 oauth2.0
    phoneGap API调用摄像头并上传图片
    ASP.NET Ajax 控件之应用一(CollapsiblePanelExtender控件的使用)
    web网页配色
    DispatcherTimer与Dispatcher小小应用
    小说ICommand
    例说INotifyPropertyChanged接口
  • 原文地址:https://www.cnblogs.com/wsnan/p/12299457.html
Copyright © 2020-2023  润新知