正則

正則表達式

一、概述

        1、 概念:符合一定規則的表達式。

        2、 作用:用於專門操作字符串。

        3、 特點:用於一些特定的符號來表示一些代碼操作,這樣可以簡化書寫。所以學習正則表達式,就是在學習一些特殊符號的使用。

        4、 好處:可以簡化對字符串的複雜操作。

        5、 弊端:符合定義越多,正則越長,閱讀性越差。

 

二、常見符號

       說明:X表示字符X或者匹配的規則。

1、字符

        x                  字符 x

        \\                 反斜線字符

        \t                 製表符 ('\u0009')

        \n                 新行(換行)符 ('\u000A')

        \r                 回車符 ('\u000D')

        \f                 換頁符 ('\u000C')

        \a                 報警 (bell)  ('\u0007')

2、字符類

        [abc]                    ab c(簡單類)

        [^abc]                 任何字符,除了 ab c(否定)

        [a-zA-Z]               a z A  Z,兩頭的字母包括在內(範圍)

        [a-d[m-p]]            a d m  p[a-dm-p](並集)

        [a-z&&[def]]               de f(交集)

        [a-z&&[^bc]]        a z,除了 b c[ad-z](減去)

        [a-z&&[^m-p]]     a z,而非 m p[a-lq-z](減去)

3、預定義字符類

        .                         任何字符(與行結束符可能匹配也可能不匹配)

        \d                        數字:[0-9]

        \D                       非數字: [^0-9]

        \s                        空白字符:[ \t\n\x0B\f\r]

        \S                       非空白字符:[^\s] 

        \w                       單詞字符:[a-zA-Z_0-9]

        \W                      非單詞字符:[^\w]

4、邊界匹配器

        ^                         行的開頭

        $                         行的結尾

        \b                        單詞邊界

        \B                       非單詞邊界

        \A                       輸入的開頭

        \G                       上一個匹配的結尾

        \Z                       輸入的結尾,僅用於最後的結束符(如果有的話)

        \z                        輸入的結尾

5Greedy數量詞

        X?                       X,一次或一次也沒有

        X*                       X,零次或多次

        X+                       X,一次或多次

        X{n}                    X,恰好 n

        X{n,}                   X,至少 n

        X{n,m}                X,至少 n次,但是不超過 m 

6、組和捕獲

       捕獲組可以通過從左到右計算其開括號來編號。例如,在表達式 ((A)(B(C)))中,存在四個這樣的組:

                    1     ((A)(B(C)))

                    2     \A

                    3     (B(C))

                    4     (C)

       組零始終代表整個表達式。在替換中常用$匹配組的內容。

 

三、正則表達式具體功能

        主要有四種具體功能:匹配、切割、替換和獲取

1、匹配:String類中的booleanmatches(String regex)方法。用規則匹配整個字符串,只要有一處不符合規則,就匹配結束,返回false

示例: 

[java] view plain copy
  1. class  MatchesDemo  
  2. {  
  3.     /* 
  4.     對QQ號碼進行校驗 
  5.     要求:5~15  0不能開頭,只能是數字 
  6.     */  
  7.     //方式一,不用正則表達式  
  8.     public static void qqCheck_1(String qq)  
  9.     {  
  10.         if (!qq.startsWith("0"))  
  11.         {  
  12.             if (qq.length()>=5&&qq.length()<=15)  
  13.             {  
  14.                 try  
  15.                 {  
  16.                     Long l=Long.parseLong(qq);//利用封裝基本數據類型出現非數字報異常的特點  
  17.                     System.out.println(qq);  
  18.                 }  
  19.                 catch (NumberFormatException e)  
  20.                 {  
  21.                     System.out.println("包含非法字符!");  
  22.                 }  
  23.             }  
  24.             else  
  25.                 System.out.println("你輸入的長度非法!");  
  26.         }  
  27.         else  
  28.             System.out.println("沒有0開頭的號碼,請重輸!");  
  29.     }  
  30.       
  31.     //方式二,用正則來實現  
  32.     public static void qqCheck_2(String qq)  
  33.     {  
  34.         String regex="[1-9]\\d{4,14}";  
  35.         if (qq.matches(regex))//用String類中matches方法來匹配  
  36.         {  
  37.             System.out.println(qq);  
  38.         }  
  39.         else  
  40.             System.out.println(qq+":是非法的號碼!");  
  41.   
  42.     }  
  43.   
  44.   
  45.     /* 
  46.         匹配 
  47.         手機號段只有 13xxx 15xxx 18xxxx 
  48.     */  
  49.   
  50.     public static void phoneCheck(String phone)  
  51.     {  
  52.         String regex="1[358]\\d{9}";  
  53.         if (phone.matches(regex))  
  54.         {  
  55.             System.out.println(phone+":::is ok..");  
  56.         }  
  57.         else  
  58.             System.out.println("手機號碼輸入有誤!");  
  59.     }  
  60.   
  61.   
  62.     public static void main(String[] args)   
  63.     {  
  64.         String qq="125696";  
  65.         qqCheck_1(qq);//不用正則的方式  
  66.         qqCheck_2(qq);//用正則的方式  
  67.   
  68.         String phone="13345678910";  
  69.         phoneCheck(phone);//匹配手機號碼是否正確  
  70.     }  
  71. }  

2、切割:String類中的String[]split(String regex)方法。

示例:

[java] view plain copy
  1. class SplitDemo   
  2. {  
  3.   
  4.     public static void main(String[] args)   
  5.     {  
  6.         String regex1="\\.";//按 .切  
  7.         String regex2=" +";//按空格切,可能有一個空格或者多個空格  
  8.         String regex3="(.)\\1+";//按照出現兩次或者以上的疊詞切  
  9.         String[] arr="192.168.1.62".split(regex1);//按 . 切  
  10.         print(arr);  
  11.   
  12.         arr ="wo  shi   shui    545  21     3".split(regex2);//按空格切  
  13.         print(arr);  
  14.   
  15.         arr="erkktyqqquizzzzzo".split(regex3);//按疊詞切  
  16.         print(arr);   
  17.     }  
  18.   
  19.     //遍歷  
  20.     public static void print(String[] arr)  
  21.     {  
  22.         for (String s : arr)  
  23.         {  
  24.             System.out.println(s);  
  25.         }  
  26.     }  
  27. }  

說明:

        按疊詞完成切割:爲了讓規則被重用,可將規則封裝成一個組,用()完成。組的出現都有編號,從1開始。想要使用已有的組可通過\nn就是組的編號)的形式來獲取。

        對於組中所匹配的字符,可以用$n來獲取。$在正則中表示行的結尾,所以出現在正則中不能用來表示組,一般用於替換中。如下面功能中。

3、替換: String replaceAll(String regex,String replacement)方法。

示例:

[java] view plain copy
  1. class ReplaceDemo   
  2. {  
  3.     public static void main(String[] args)   
  4.     {  
  5.         String regex1="\\d{5,}";//將字符串中數字替換成#  
  6.         String regex2="(.)\\1+";//將疊詞替換爲一個  
  7.   
  8.         String s1="erej569831217woshi2659810wosxs12356f";  
  9.         s1=s1.replaceAll(regex1,"#");//將字符串中的數字替換成#  
  10.   
  11.         String s2="erkktyqqquizzzzzo";  
  12.         s2=s2.replaceAll(regex2,"$1");//將疊詞替換爲一個,其中$1表示符合組中一個字符  
  13.   
  14.         System.out.println("s1:"+s1);  
  15.         System.out.println("s2:"+s2);  
  16.     }  
  17. }  

4、獲取:將字符串中的符合規則的子串取出。

操作步驟:

        1)將正則表達式封裝成對象。

        2)讓正則對象和要操作的字符串相關聯。

        3)關聯後,獲取正則匹配引擎。

        4)通過引擎對符合規則的子串進行操作,比如取出。

示例:

[java] view plain copy
  1. import java .util.regex.*;  
  2. class  PatternDemo  
  3. {  
  4.     public static void main(String[] args)   
  5.     {  
  6.         String s= "ming tian jiu yao fang jia le ,da jia。";  
  7.         String regex="\\b[a-z]{4}\\b";  
  8.         get(s,regex);  
  9.     }  
  10.     public static void get(String s,String regex)  
  11.     {  
  12.         //將規則封裝成對象。  
  13.         Pattern p=Pattern.compile(regex);  
  14.         //讓正則對象和要作用的字符串相關聯。獲取匹配器對象。  
  15.         Matcher m=p.matcher(s);  
  16.   
  17.         //System.out.println(m.matches());  
  18.         //其實String類中的matches方法。用的就是Pattern和Matcher對象來完成的。  
  19.         //只不過被String的方法封裝後,用起來較爲簡單。但是功能卻單一。  
  20.   
  21.         while(m.find())//find()方法是將規則作用到字符串上,並進行符合規則的子串查找。  
  22.         {  
  23.             System.out.println(m.group());//group()方法用於獲取匹配後結果。  
  24.             System.out.println(m.start()+"...."+m.end());  
  25. //start()和end()分別表示匹配字符的開始和結尾的索引  
  26.         }  
  27.     }  
  28. }  

 

四、練習

四種功能的選擇(思路方式):

        1)如果只想知道該字符是否對是錯,使用匹配。

        2)想要將已有的字符串變成另一個字符串,替換。

        3)想要按照自定的方式將字符串變成多個字符串。切割。獲取規則以外的子串。

        4)想要拿到符合需求的字符串子串,獲取。獲取符合規則的子串。

練習1

[java] view plain copy
  1. /* 
  2. 練習: 
  3. 需求:將下列字符串轉成:我要學編程 
  4. "我我...我..我要...要...要要....學學....學學學......編編編...程...程程...." 
  5.  
  6. 思路: 
  7. 將已有字符串變成另一個字符串。使用替換功能。 
  8. 1、可以先將 . 去掉。 
  9. 2、再將多個重複的內容變成單個內容。 
  10.  
  11. */  
  12. class  ReplaceTest  
  13. {  
  14.     public static void main(String[] args)   
  15.     {  
  16.         String s="我我...我..我要...要...要要....學學....學學學......編編編...程...程程....";  
  17.         System.out.println(s);  
  18.   
  19.         String regex="\\.+";//先將 . 去掉  
  20.         s=s.replaceAll(regex,"");//去掉 .  
  21.         System.out.println(s);  
  22.   
  23.         regex="(.)\\1+";//將重複的內容變成單個內容  
  24.         s=s.replaceAll(regex,"$1");//去重  
  25.         System.out.println(s);  
  26.     }  
  27. }  

練習2

[java] view plain copy
  1. /* 
  2. 需求: 
  3. 將ip地址進行地址段順序的排序。 
  4. 192.68.1.254 102.49.23.013 10.10.10.10 2.2.2.2 8.109.90.301 
  5.  
  6. 思路: 
  7. 還按照字符串自然順序,只要讓他們每一段都是3位即可。 
  8. 1、按照每一段需要的最多的0進行補齊,那麼每一段就會至少保證有3位。 
  9. 2、將每一段只保留3位。這樣,所有的ip地址都是每一段3位。 
  10.  
  11. */  
  12. import java.util.*;  
  13.   
  14. class  IPSortTest  
  15. {  
  16.     public static void main(String[] args)   
  17.     {  
  18.         String ip="192.68.1.254 102.49.23.013 10.10.10.10 2.2.2.2 8.109.90.301";  
  19.         System.out.println(ip);  
  20.   
  21.         String regex="(\\d+)";  
  22.         ip=ip.replaceAll(regex,"00$1");//保證每段至少都有三位-------------  
  23.         System.out.println(ip);  
  24.   
  25.         regex="0*(\\d{3})";  
  26.         ip=ip.replaceAll(regex,"$1");//每段只保留三位  
  27.         System.out.println(ip);  
  28.   
  29.         regex=" ";  
  30.         String[] arr=ip.split(regex);//按照空格切  
  31.           
  32.         //定義一個TreeSet集合,利用元素自然排序  
  33.         TreeSet<String > ts=new TreeSet<String>();  
  34.         for (String str : arr )  
  35.         {  
  36.             ts.add(str);//添加  
  37.         }  
  38.           
  39.         regex="0*(\\d)";//把每段前面多餘的0替換掉  
  40.         for (String s : ts)  
  41.         {  
  42.             System.out.println(s.replaceAll(regex,"$1"));//把每段前面多餘的0替換掉  
  43.         }  
  44.     }  
  45. }  

練習3

[java] view plain copy
  1. //需求:對郵件地址進行校驗。  
  2.   
  3. class  CheckMail  
  4. {  
  5.     public static void main(String[] args)   
  6.     {  
  7.         String mail="[email protected]";  
  8.         String regex="\\w+@[a-zA-Z0-9]+(\\.[a-zA-Z]+){1,3}";//較爲精確  
  9.         regex="\\w+@\\w+(\\.\\w+)+";//相對不太精確的匹配。  
  10.   
  11.         boolean b=mail.matches(regex);  
  12.         System.out.println(b);  
  13.     }  
  14. }  

練習4

[java] view plain copy
  1. /* 
  2. 網絡爬蟲(蜘蛛) 
  3. 實際上是一個功能,用於蒐集網絡上的指定信息 
  4. 需求:可用於收集郵箱,qq號等之類的信息。 
  5. 應用:如通過關鍵字搜索blog,實際就是使用的“蜘蛛”,通過查找關鍵字獲取相關的blog 
  6. */  
  7.   
  8. import java.net.*;  
  9. import java.util.regex.*;  
  10. import java.io.*;  
  11.   
  12. class  Spider  
  13. {  
  14.     public static void main(String[] args)throws Exception  
  15.     {  
  16.         //getFileMail();  
  17.         getWebMail();  
  18.           
  19.     }  
  20.   
  21.     //獲取網頁中mail  
  22.     public static  void getWebMail()throws Exception  
  23.     {  
  24.         //封裝網頁地址  
  25.         URL url=new URL("http://tieba.baidu.com/p/1390896758");  
  26.         //連接服務器  
  27.         URLConnection conn=url.openConnection();  
  28.         //帶緩衝區的網頁讀取流  
  29.         BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
  30.         String line=null;  
  31.           
  32.         //定義匹配郵件地址的正則表達式  
  33.         String regex="\\w+@\\w+(\\.\\w+)+";  
  34.         Pattern p=Pattern.compile(regex);//封裝正則表達式  
  35.         //讀取網頁數據  
  36.         while ((line=br.readLine())!=null)  
  37.         {  
  38.             //正則關聯數據  
  39.             Matcher m=p.matcher(line);  
  40.             //尋找匹配郵箱  
  41.             while (m.find())  
  42.             {  
  43.                 System.out.println(m.group());//輸出匹配郵箱  
  44.             }         
  45.         }     
  46.     }  
  47.   
  48.     //獲取指定文檔中的郵件地址。使用獲取功能。Pattern  Matcher  
  49.     public static void getFileMail()throws Exception  
  50.     {  
  51.         //將文件封裝成對象  
  52.         File file=new File("E:\\Java Study\\Practice\\day25\\mail.txt");  
  53.         //創建帶緩衝區的讀取流  
  54.         BufferedReader br=new BufferedReader(new FileReader(file));  
  55.         String line=null;  
  56.   
  57.         //定義正則表達式  
  58.         String regex="\\w+@[a-zA-Z]+(\\.[a-zA-z]+)+";  
  59.         //創建Pattern對象,封裝正則表達式  
  60.         Pattern p=Pattern.compile(regex);  
  61.   
  62.         //讀取文件中數據  
  63.         while ((line=br.readLine())!=null)  
  64.         {     
  65.               
  66.             //關流字符串  
  67.             Matcher m=p.matcher(line);  
  68.             while (m.find())//尋找匹配的字符串  
  69.             {  
  70.                 System.out.println(m.group());//輸出匹配的字符串  
  71.             }  
  72.         }  
  73.     }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章