加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式

发布时间:2020-12-14 06:18:55 所属栏目:百科 来源:网络整理
导读:正则表达式 ?定义:符合一定规则的表达式 ? ?判断功能: ??String类的public boolean matches(String regex) ?? ?分割功能: ??String类的public String[] split(String regex) ? ?替换功能: ??String类的public String replaceAll(String regex,String rep

正则表达式
?定义:符合一定规则的表达式
?
?判断功能:
??String类的public boolean matches(String regex)
??
?分割功能:
??String类的public String[] split(String regex)
?
?替换功能:
??String类的public String replaceAll(String regex,String replacement)
?
?获取功能:
??Pattern和Matcher类的使用
???Pattern p=Pattern.compile(String regex);通过模式器Pattern的
????静态方法compile(String regex)方法得到模式器对象
???Matcher m=p.matcher(String str);通过模式器对象调用
????matcher(String str)方法得到匹配器Matcher对象
???Matcher类的public boolean find():查找有没有满足条件的子串
???Matcher类的public String group():获取满足条件的子串
?
?
?示例:
??1.检查QQ格式是否正确(matches()方法):
?? 要求必须是5-15位数字且0不能开头

            public class Demo
            {
                public static void main(String[] args)
                {
                    String qqNumber="此处填QQ号";
                    String regex="[1-9][0-9]{4,14}";
                    boolean flag=qqNumber.matches(regex);
                    System.out.print(flag);
                }
            }

?


??2.根据正则表达式分割字符串(split(String regex)方法)

            public class Demo1
            {
                public static void main(String[] args)
                {
                    String s="a-b-c-d-e-f-g";
                    String regex="-";
                    String[] str=s.split(regex);
                    for(String ss::str)
                    {
                    System.out.print(ss);
                    }//输出结果为:abcdefg
                }
            }

?


??3.根据正则表达式替换字符串中子串

   public class Demo2
   {
    public static void main(String[] args)
    {
     String s="a-b-c-d-e-f-g";
     String regex="-";
     String str=s.replaceAll(regex,"**");
     System.out.print(str)//输出结果为:a**b**c**d**e**f**g
    }
   }

?


??4.根据模式匹配器获取子串

   public class Demo2
   {
    public static void main(String[] args)
    {
     String s="a-b-c-d-e-f-g";
     String regex="-";
     Pattern p=Pattern.compile(regex);
     Matcher m=p.matcher(s);
     while(m.find())
     {
      System.out.print(m.group());
     }//输出结果为:------
    }
   }

?

???注意事项:??1.此文的String regex正则表达式只是简单的模式,详细请查看API??2.运用模式匹配器获得满足正则表达式字符串时,需要先用find()方法??? 判断是否还有指定字符串,再进行group()。??3.find()在API中的解释:此方法从匹配器区域的开头开始,??? 如果该方法的前一次调用成功了并且从那时开始匹配器没有被重置,??? 则从以前匹配操作没有匹配的第一个字符开始。(即,如果前一次匹配成功,??? 并且匹配器没有刷新,那么就接着匹配下一个满足的字符串,直到没有满足??? 的则返回false)??4.group()在API中的解释:返回由以前匹配操作所匹配的输入子序列(即,返回??? find()方法匹配成功的字符串)??? ??练习题:??1.获取下面这个字符串中由三个字符组成的单词??? da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu???2.校验邮箱??3.判断手机号码是否满足???

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读