温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

黑马程序员——正则表达式篇

发布时间:2020-07-10 19:31:22 来源:网络 阅读:345 作者:optimisticpig 栏目:移动开发

------- android培训、java培训、期待与您交流! ----------


正则表达式:符合一定规则的表达式。

作用:用于专门操作字符串。

特点:用一些特定的符合来表示一些代码操作,这样就简化书写。

所以学习正则表达式,就是在学习一些特殊符号的使用。


好处:可以简化对字符串的复杂操作。

弊端:符合定义越多,正则表达式越长,阅读性越差。


具体操作功能:

1,匹配:String matches(regex);用规则匹配整改字符串,只要有一处不符合规则,就匹配结束,返回false

2,切割:String split();

3,替换:String replaceAll();

class  RegexDemo
{
    public static void main(String[] args)
    {
        //checkQQ();
        //demo();
        //checkTel();
        //splitDemo();
        String str ="g12864367946hjpwfb34999qo8ghowqb5796";
        replaceAllDemo(str,"\\d{5,}","#");
        String str1 = "qwwwwwoefaffqoeewiurouu";
        replaceAllDemo(str1,"(.)\\1+","#");//将叠词替换成#;
        replaceAllDemo(str1,"(.)\\1+","$1");//将重叠的字符替换成一个字符。
        //$1表示引用前面组中的字符。
        //因为字符串str、str1都被默认为0组,所以正则表达式中的组从1开始。
    }
    public static void replaceAllDemo(String str,String reg,String newStr)
    {
        str = str.replaceAll(reg,newStr);
        System.out.println(str);
    }
    public static void splitDemo()
    {
        //String str="zhangsan.lisi.wangwu";
        //str = "c:\\abc\\a.txt";
        String str = "erkkandfkkaoiqqfui";//按叠词切割。
        //String reg = " +";//规则是空格出现一次或多次。
        //String reg  = "\\.";//因为正则表达式中的.表示任意字符。所以用\.表示点,在字符串中用\\.表示。
        //String reg = "\\\\";
        String reg = "(.)\\1";
        //可以将规则封装装成一个组。用()完成。组的出现都有编号。
        //从1开始。想要使用已有的组可以通过 \n的形式来获取。(n为组的编号。)
        //(.)表示任意字符为组。\\1表示捕获组。
        //
        String[] arr = str.split(reg);
        for(String s:arr)
        {
            System.out.println(s);
        }
    }
    /*
    匹配:
    手机号段只有13xxx 15xxx 18xxx
    */
    public static void checkTel()
    {
        String tel = "13596875464";
        String reg = "[1][358]\\d{9}";
        boolean b = tel.matches(reg);
        System.out.println(b);
    }
    public static void demo()
    {
        String str = "b";
        //String reg = "[a-zA-Z]\\d";//[a-zA-Z][0-9]
        //String reg = "[a-zA-Z]\\d?";//表示第一位是字母,以后数字出现一次或没有。
        String reg = "[a-zA-Z]\\d*";//表示第一位是字母,以后数字出现零次或多次。
        boolean b = str.matches(reg);
        System.out.println(b);
    }
    public static void checkQQ()
    {
        String qq = "13463131";
        String regex = "[1-9]\\d{4,14}";//表示第一位数字为1-9,\\d{4,14}表示4-14为的数字为0-9
        boolean flag =qq.matches(regex);
        if (flag)
            System.out.println(qq+"....is OK");
        else
            System.out.println(qq+"....不合法");
    }
    /*
    对QQ号码进行校验
    要求:5~15位,0不能开头,只能是数字。
    这种方式,使用了String类中的方法,进行组合完成了需求,但是代码过于复杂。
    */
    public static void checkQQ_1()
    {
        String qq="12341";
        int len = qq.length();
        if (len>=5 && len<=15)
        {
            if (!qq.startsWith("0"))//Integer.parseInt("12a"); 当含有不是int的数据时,出现NumberFormatException.
            {
                try
                {
                    long l = Long.parseLong(qq);
                    System.out.println("qq:"+qq);
                }
                catch (NumberFormatException e)
                {
                    throw new RuntimeException("含有非法字符");
                }
                                     
                /*
                char[] ch = qq.toCharArray();
                boolean flag = true;
                for (int x =0;x<ch.length ;x++ )
                {
                    if (!(ch[x]>+'0' && ch[x]<='9'))
                    {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {
                    System.out.println("qq:"+qq);
                }
                else
                {
                    System.out.println("含有非法字符");
                }
                */
                                     
            }
            else
            {
                System.out.println("不能以0开头");
            }
        }
    }
}

正则表达式的第四功能。

4,获取:将字符串中符合规则的子串取出。

操作步骤:

1,将正则表达式封装成对象。

2,让正则对象和要操作的字符串相关联。

3,关联后,获取正则匹配引擎。

4,通过引擎


import java.util.regex.*;
class RegexDemo2
{
    public static void main(String[] args)
    {
        getDemo();
    }
    public static void getDemo()
    {
        String str = "ming tian jiu yao fang jia le";
        //String qq = "135648";
        //Stringreg = "[1-9]\\d{4-14}";
        String reg = "\\b[a-z]{3}\\b";//\\b表示单词边界。
        //将规则封装成对象。
        Pattern p = Pattern.compile(reg);
        //让正则对象和要作用的字符串关联,获取匹配器对象。
        Matcher m = p.matcher(str);
        //System.out.println(m.matches());
        //String类中的mathces方法。用的就是Pattern和Matcher对象来完成的。
        //只不过被String的方法封装后,用起来比较简单。但是功能却单一。
                      
        while(m.find())//将规则作用到字符串上,并进行符合规则的子串查找。
        {
            System.out.println(m.group());//用于获取匹配后的结果。
        }
    }
}


练习:

import java.util.*;
class RegexTest
{
    public static void main(String[] args)
    {
        //test_1();
        //sort();
        checkMail();
    }
    /*
    需求:对邮件地址进行校验。
    */
    public static void checkMail()
    {
        String mail = "abc12@sina.com.cn.net";
        //                                  //包括.com.cn 但有一定的限制。   
        String reg = "\\w{1,12}@[a-zA-Z0-9]+(\\.[a-zA-Z]+){1,3}";//较为精确的匹配。
        reg = "\\w+@\\w+(\\.\\w+)+";//相对不太精确的匹配。
        //mail.indexOf("@")!=-1; 只要有@就行。
               
        System.out.println(mail.matches(reg));
    }
    /*
    需求:
    将下列字符串转成:我要学编程。
    到底用四中功能中的哪一个呢?或者那几个呢?
    思路方式:
    1,如果只想知道该字符是对是错,使用匹配。
    2,想要将已有的字符串变成另一个字符串,替换。
    3,想要按照自定义的方式将字符串变成多个字符串。切割。获得规则以外的子串。
    4,想要拿到符合要求的字符串,获取。获取符合规则的子串。
    */
    public static void test_1()
    {
        String str = "我我...我我...我要..要要...要要...学学学....学学...编编编...编程..程.程程...程...程";
        /*
        将已有字符串变成另一个字符串。使用替换功能。
        1,可以先将.去掉。
        2,在将多个重复的内容变成单个内容。
        */
        String s =str.replaceAll("\\.+","").replaceAll("(.)\\1+","$1");
        System.out.println(s);
    }
    /*
    192.68.1.254 102.49.23.013 10.10.10.10 2.2.2.2 8.109.90.30
    将ip地址进行地址段的排序。
    还安装字符串自然顺序排序,只有让他们每一段都是3为即可。
    1,按照每一段需要的最多的0进行补齐,那么每一段就会至少保证有3位。
    2,将每一段只保留3位。这样所有的ip地址都是每一段3位。
    */
    public static void sort()
    {
        String ip = "192.68.1.254 102.49.23.013 10.10.10.10 2.2.2.2 8.109.90.30";
        //当规则需要被重用时,用组封装。
        ip = ip.replaceAll("(\\d+)","00$1");
        ip = ip.replaceAll("0*(\\d{3})","$1");//将需要的3位数字封装成组。
        String[] arr = ip.split(" ");
               
        TreeSet<String> ts = new TreeSet<String>();
        for (String s:arr )
        {
            ts.add(s);
        }
        for(String s: ts)
        {
            System.out.println(s.replaceAll("0*(\\d+)","$1"));
        }
        /*
        Arrays.sort(arr);
        for(String s :arr)
        {
            System.out.println(s.replaceAll("0*(\\d+)","$1"));
        }
        */
    }
}



网页爬虫

/*
网页爬虫(蜘蛛)
*/
import java.io.*;
import java.util.regex.*;
import java.net.*;
class RegexTest2
{
    public static void main(String[] args) throws Exception
    {
        getMails_1();
    }
    public static void getMails_1()throws Exception
    {
        URL url  = new URL("http://127.0.0.1:8080/myweb/mail.html");
        URLConnection conn = url.openConnection();
        BufferedReader bufIn = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        String mailreg ="\\w{6,12}@[a-zA-Z0-9]+(\\.[a-zA-Z]+){1,3}";
        Pattern p = Pattern.compile(mailreg);
          
        while ((line=bufIn.readLine())!=null)
        {
            Matcher m = p.matcher(line);
            while (m.find())
            {
                System.out.println(m.group());
            }
              
        }
    }
    /*
    获取指定文档中的邮件地址。
    使用获取功能。Pattern Matcher
      
    */
    public static void getMails()throws Exception
    {
        BufferedReader bufr =
            new BufferedReader(new FileReader("mail.txt"));
        String line = null;
        String reg ="\\w{6,12}@[a-zA-Z0-9]+(\\.[a-zA-Z]+){1,3}";
        Pattern p = Pattern.compile(reg);
          
        while ((line=bufr.readLine())!=null)
        {
            Matcher m = p.matcher(line);
            while (m.find())
            {
                System.out.println(m.group());
            }
              
        }
    }
}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI