黑馬程式員—java基礎—————– Regex

來源:互聯網
上載者:User

Regex:符合一定規則的運算式。
    作用:用於專門操作字串。
    特點:用於一些特定的符號來表示一些代碼操作。這樣就簡化書寫

    好處:可以簡化對字串的複雜操作。
    弊端:符號定義越多,正則越長,閱讀性越差。

    具體操作功能:    

      1,匹配:String  matches方法。用規則匹配整個字串,只要有一處不符合規則,就匹配結束,返回false。

/*匹配手機號段只有 13xxx 15xxx 18xxxx*/public static void checkTel(){String tel = "16900001111";String telReg = "1[358]\\d{9}";System.out.println(tel.matches(telReg));}public static void demo(){String str = "b23a23456789";String reg = "[a-zA-Z]\\d*";boolean b= str.matches(reg);System.out.println(b);}public static void checkQQ(){String qq = "123a454";String regex = "[1-9]\\d{4,14}";boolean flag = qq.matches(regex);if(flag)System.out.println(qq+"...is ok");elseSystem.out.println(qq+"... 不合法");}/*對QQ號碼進行校正要求:5~15  0不能開頭,只能是數字這種方式,使用了String類中的方法,進行組合完成了需求。但是代碼過於複雜。*/public static void checkQQ_1(){String qq = "1882345a0";int len = qq.length();if(len>=5 && len<=15){if(!qq.startsWith("0"))//Integer.parseInt("12a");NumberFormatException{try{long l = Long.parseLong(qq);System.out.println("qq:"+l);}catch (NumberFormatException e){System.out.println("出現非法字元.......");}/*char[] arr = qq.toCharArray();//123a4boolean flag = true;for(int x=0;x<arr.length; x++){if(!(arr[x]>='0' && arr[x]<='9')){flag = false;break;}}if(flag){System.out.println("qq:"+qq);}else{System.out.println("出現非法字元");}*/}else{System.out.println("不可以0開頭");}}else{System.out.println("長度錯誤");}}

 
      2,切割:String split();

public static void splitDemo(String str,String reg){//String reg = " +";//按照多個空格來進行切割String[] arr = str.split(reg);  System.out.println(arr.length);for(String s : arr){System.out.println(s);}}

      3,替換:String replaceAll(regex,str);如果regex中有定義組,可以在第二參數中通過$符號擷取Regex中的已有的組。

public static void replaceAllDemo(String str,String reg,String newStr){                   String str = "wer1389980000ty1234564uiod234345675f";//將字串中的數組替換成#。//replaceAllDemo(str,"\\d{5,}","#");String str1 = "erkktyqqquizzzzzo";//將疊詞替換成$.  //將重疊的字元替換成單個字母。zzzz->zreplaceAllDemo(str1,"(.)\\1+","$1");str = str.replaceAll(reg,newStr);System.out.println(str);} 

      4,擷取:將字串中的符合規則的子串取出。

          操作步驟:
          1,將Regex封裝成對象。
          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 ,da jia。";System.out.println(str);String reg = "\\b[a-z]{4}\\b";//將規則封裝成對象。Pattern p = Pattern.compile(reg);//讓正則對象和要作用的字串相關聯。擷取匹配器對象。Matcher m  = p.matcher(str);//System.out.println(m.matches());//其實String類中的matches方法。用的就是Pattern和Matcher對象來完成的。//只不過被String的方法封裝後,用起來較為簡單。但是功能卻單一。//boolean b = m.find();//將規則作用到字串上,並進行符合規則的子串尋找。//System.out.println(b);//System.out.println(m.group());//用於擷取匹配後結果。//System.out.println("matches:"+m.matches());while(m.find()){System.out.println(m.group());System.out.println(m.start()+"...."+m.end());}}}

 

/*需求:對郵件地址進行校正。*/public static void checkMail(){String mail = "abc12@sina.com";mail = "1@1.1";String reg = "[a-zA-Z0-9_]+@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+";//較為精確的匹配。reg = "\\w+@\\w+(\\.\\w+)+";//相對不太精確的匹配。//mail.indexOf("@")!=-1System.out.println(mail.matches(reg));}/*需求:將下列字串轉成:我要學編程.到底用四種功能中的哪一個呢?或者哪幾個呢?思路方式:1,如果只想知道該字元是否對是錯,使用匹配。2,想要將已有的字串變成另一個字串,替換。3,想要按照自定的方式將字串變成多個字串。切割。擷取規則以外的子串。4,想要拿到符合需求的字串子串,擷取。擷取符合規則的子串。*/public static void test_1(){String str = "我我...我我...我要..要要...要要...學學學....學學...編編編...編程..程.程程...程...程";/*將已有字串變成另一個字串。使用 替換功能。1,可以先將 . 去掉。2,在將多個重複的內容變成單個內容。*/str = str.replaceAll("\\.+","");System.out.println(str);str = str.replaceAll("(.)\\1+","$1");System.out.println(str);}/*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 ipSort(){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");System.out.println(ip);ip = ip.replaceAll("0*(\\d{3})","$1");System.out.println(ip);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"));}}

 

/*網頁爬蟲(蜘蛛)*/import java.io.*;import java.util.regex.*;import java.net.*;import java.util.*;class RegexTest2 {public static void main(String[] args) throws Exception{getMails_1();}public static void getMails_1()throws Exception{URL url = new URL("http://192.168.1.254:8080/myweb/mail.html");URLConnection conn = url.openConnection();BufferedReader bufIn = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line = null;String mailreg = "\\w+@\\w+(\\.\\w+)+";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 mailreg = "\\w+@\\w+(\\.\\w+)+";Pattern p = Pattern.compile(mailreg);while((line=bufr.readLine())!=null){Matcher m = p.matcher(line);while(m.find()){System.out.println(m.group());}}}}

 

java.util.regex
類 Pattern
java.lang.Object  java.util.regex.Pattern


構造 匹配
 
字元
x 字元 x
\\ 反斜線字元
\0n 帶有八進位值 0 的字元 n (0 <= n <= 7)
\0nn 帶有八進位值 0 的字元 nn (0 <= n <= 7)
\0mnn 帶有八進位值 0 的字元 mnn(0 <= m <= 3、0 <= n <= 7)
\xhh 帶有十六進位值 0x 的字元 hh
\uhhhh 帶有十六進位值 0x 的字元 hhhh
\t 定位字元 ('\u0009')
\n 新行(換行)符 ('\u000A')
\r 斷行符號符 ('\u000D')
\f 換頁符 ('\u000C')
\a 警示 (bell) 符 ('\u0007')
\e 轉義符 ('\u001B')
\cx 對應於 x 的控制符
 
字元類
[abc] a、b 或 c(簡單類)
[^abc] 任何字元,除了 a、b 或 c(否定)
[a-zA-Z] a 到 z 或 A 到 Z,兩頭的字母包括在內(範圍)
[a-d[m-p]] a 到 d 或 m 到 p:[a-dm-p](並集)
[a-z&&[def]] d、e 或 f(交集)
[a-z&&[^bc]] a 到 z,除了 b 和 c:[ad-z](減去)
[a-z&&[^m-p]] a 到 z,而非 m 到 p:[a-lq-z](減去)
 
預定義字元類
. 任何字元(與行結束符可能匹配也可能不匹配)
\d 數字:[0-9]
\D 非數字: [^0-9]
\s 空白字元:[ \t\n\x0B\f\r]
\S 非空白字元:[^\s]
\w 單詞字元:[a-zA-Z_0-9]
\W 非單詞字元:[^\w]
 
POSIX 字元類(僅 US-ASCII)
\p{Lower} 小寫字母字元:[a-z]
\p{Upper} 大寫字母字元:[A-Z]
\p{ASCII} 所有 ASCII:[\x00-\x7F]
\p{Alpha} 字母字元:[\p{Lower}\p{Upper}]
\p{Digit} 十進位數字:[0-9]
\p{Alnum} 字母數字字元:[\p{Alpha}\p{Digit}]
\p{Punct} 標點符號:!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
\p{Graph} 可見字元:[\p{Alnum}\p{Punct}]
\p{Print} 可列印字元:[\p{Graph}\x20]
\p{Blank} 空格或定位字元:[ \t]
\p{Cntrl} 控制字元:[\x00-\x1F\x7F]
\p{XDigit} 十六進位數字:[0-9a-fA-F]
\p{Space} 空白字元:[ \t\n\x0B\f\r]

 

邊界匹配器
^ 行的開頭
$ 行的結尾
\b 單詞邊界
\B 非單詞邊界
\A 輸入的開頭
\G 上一個匹配的結尾
\Z 輸入的結尾,僅用於最後的結束符(如果有的話)
\z 輸入的結尾
 
Greedy 數量詞
X? X,一次或一次也沒有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n
X{n,} X,至少 n
X{n,m} X,至少 n 次,但是不超過 m
 
Reluctant 數量詞
X?? X,一次或一次也沒有
X*? X,零次或多次
X+? X,一次或多次
X{n}? X,恰好 n
X{n,}? X,至少 n
X{n,m}? X,至少 n 次,但是不超過 m
 
Possessive 數量詞
X?+ X,一次或一次也沒有
X*+ X,零次或多次
X++ X,一次或多次
X{n}+ X,恰好 n
X{n,}+ X,至少 n
X{n,m}+ X,至少 n 次,但是不超過 m

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.