溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

黑馬程序員——正則表達(dá)式篇

發(fā)布時(shí)間:2020-07-10 19:31:22 來源:網(wǎng)絡(luò) 閱讀:359 作者:optimisticpig 欄目:移動(dòng)開發(fā)

------- android培訓(xùn)、java培訓(xùn)、期待與您交流! ----------


正則表達(dá)式:符合一定規(guī)則的表達(dá)式。

作用:用于專門操作字符串。

特點(diǎn):用一些特定的符合來表示一些代碼操作,這樣就簡化書寫。

所以學(xué)習(xí)正則表達(dá)式,就是在學(xué)習(xí)一些特殊符號(hào)的使用。


好處:可以簡化對(duì)字符串的復(fù)雜操作。

弊端:符合定義越多,正則表達(dá)式越長,閱讀性越差。


具體操作功能:

1,匹配:String matches(regex);用規(guī)則匹配整改字符串,只要有一處不符合規(guī)則,就匹配結(jié)束,返回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");//將重疊的字符替換成一個(gè)字符。
        //$1表示引用前面組中的字符。
        //因?yàn)樽址畇tr、str1都被默認(rèn)為0組,所以正則表達(dá)式中的組從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 = " +";//規(guī)則是空格出現(xiàn)一次或多次。
        //String reg  = "\\.";//因?yàn)檎齽t表達(dá)式中的.表示任意字符。所以用\.表示點(diǎn),在字符串中用\\.表示。
        //String reg = "\\\\";
        String reg = "(.)\\1";
        //可以將規(guī)則封裝裝成一個(gè)組。用()完成。組的出現(xiàn)都有編號(hào)。
        //從1開始。想要使用已有的組可以通過 \n的形式來獲取。(n為組的編號(hào)。)
        //(.)表示任意字符為組。\\1表示捕獲組。
        //
        String[] arr = str.split(reg);
        for(String s:arr)
        {
            System.out.println(s);
        }
    }
    /*
    匹配:
    手機(jī)號(hào)段只有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?";//表示第一位是字母,以后數(shù)字出現(xiàn)一次或沒有。
        String reg = "[a-zA-Z]\\d*";//表示第一位是字母,以后數(shù)字出現(xiàn)零次或多次。
        boolean b = str.matches(reg);
        System.out.println(b);
    }
    public static void checkQQ()
    {
        String qq = "13463131";
        String regex = "[1-9]\\d{4,14}";//表示第一位數(shù)字為1-9,\\d{4,14}表示4-14為的數(shù)字為0-9
        boolean flag =qq.matches(regex);
        if (flag)
            System.out.println(qq+"....is OK");
        else
            System.out.println(qq+"....不合法");
    }
    /*
    對(duì)QQ號(hào)碼進(jìn)行校驗(yàn)
    要求:5~15位,0不能開頭,只能是數(shù)字。
    這種方式,使用了String類中的方法,進(jìn)行組合完成了需求,但是代碼過于復(fù)雜。
    */
    public static void checkQQ_1()
    {
        String qq="12341";
        int len = qq.length();
        if (len>=5 && len<=15)
        {
            if (!qq.startsWith("0"))//Integer.parseInt("12a"); 當(dāng)含有不是int的數(shù)據(jù)時(shí),出現(xiàn)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開頭");
            }
        }
    }
}

正則表達(dá)式的第四功能。

4,獲?。簩⒆址蟹弦?guī)則的子串取出。

操作步驟:

1,將正則表達(dá)式封裝成對(duì)象。

2,讓正則對(duì)象和要操作的字符串相關(guān)聯(lián)。

3,關(guān)聯(lián)后,獲取正則匹配引擎。

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表示單詞邊界。
        //將規(guī)則封裝成對(duì)象。
        Pattern p = Pattern.compile(reg);
        //讓正則對(duì)象和要作用的字符串關(guān)聯(lián),獲取匹配器對(duì)象。
        Matcher m = p.matcher(str);
        //System.out.println(m.matches());
        //String類中的mathces方法。用的就是Pattern和Matcher對(duì)象來完成的。
        //只不過被String的方法封裝后,用起來比較簡單。但是功能卻單一。
                      
        while(m.find())//將規(guī)則作用到字符串上,并進(jìn)行符合規(guī)則的子串查找。
        {
            System.out.println(m.group());//用于獲取匹配后的結(jié)果。
        }
    }
}


練習(xí):

import java.util.*;
class RegexTest
{
    public static void main(String[] args)
    {
        //test_1();
        //sort();
        checkMail();
    }
    /*
    需求:對(duì)郵件地址進(jìn)行校驗(yàn)。
    */
    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+)+";//相對(duì)不太精確的匹配。
        //mail.indexOf("@")!=-1; 只要有@就行。
               
        System.out.println(mail.matches(reg));
    }
    /*
    需求:
    將下列字符串轉(zhuǎn)成:我要學(xué)編程。
    到底用四中功能中的哪一個(gè)呢?或者那幾個(gè)呢?
    思路方式:
    1,如果只想知道該字符是對(duì)是錯(cuò),使用匹配。
    2,想要將已有的字符串變成另一個(gè)字符串,替換。
    3,想要按照自定義的方式將字符串變成多個(gè)字符串。切割。獲得規(guī)則以外的子串。
    4,想要拿到符合要求的字符串,獲取。獲取符合規(guī)則的子串。
    */
    public static void test_1()
    {
        String str = "我我...我我...我要..要要...要要...學(xué)學(xué)學(xué)....學(xué)學(xué)...編編編...編程..程.程程...程...程";
        /*
        將已有字符串變成另一個(gè)字符串。使用替換功能。
        1,可以先將.去掉。
        2,在將多個(gè)重復(fù)的內(nèi)容變成單個(gè)內(nèi)容。
        */
        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地址進(jìn)行地址段的排序。
    還安裝字符串自然順序排序,只有讓他們每一段都是3為即可。
    1,按照每一段需要的最多的0進(jìn)行補(bǔ)齊,那么每一段就會(huì)至少保證有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";
        //當(dāng)規(guī)則需要被重用時(shí),用組封裝。
        ip = ip.replaceAll("(\\d+)","00$1");
        ip = ip.replaceAll("0*(\\d{3})","$1");//將需要的3位數(shù)字封裝成組。
        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"));
        }
        */
    }
}



網(wǎng)頁爬蟲

/*
網(wǎng)頁爬蟲(蜘蛛)
*/
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問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI