Java正則表達式入門

一:什麼是正則表達式

    1.定義:正則表達式是一種可以用於模式匹配和替換的規範,一個正則表達式就是由普通的字符(例如字符a到z)以及特殊字符(元字符)組成的文字模式,它 用以描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作爲一個模板,將某個字符模式與所搜索的字符串進行匹配。

    2.用途:

  • 字符串匹配(字符匹配)
  • 字符串查找
  • 字符串替換
  • 字符串分割

    例如:

  • 從網頁中揪出email地址
  • IP地址是否正確
  • 從網頁中揪出鏈接

    3.java中處理正則表達式的類:

  • java.lang.String
  • java.util.regex.Pattern:模式類:字符串要被匹配的這麼一個模式,該模式本身已經被編譯過,使用的話效率要高很多。
  • java.util.regex.Matcher:匹配類:這個模式匹配某個字符串所產生的結果,這個結果可能會有很多個。

    4:下面通過一個小程序簡單介紹一下正則表達式

 

複製代碼
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) {
        //matches()判斷字符串是否匹配某個表達式,"."表示任何一個字符
        p("abc".matches("..."));
        //將字符串"a2389a"中的數字用*替換,\d 表示“0--9”數字
        p("a2389a".replaceAll("\\d", "*"));
        //將任何是a--z的字符串長度爲3的字符串進行編譯,這樣可以加快匹配速度
        Pattern p = Pattern.compile("[a-z]{3}");
        //進行匹配,並將匹配結果放在Matcher對象中
        Matcher m = p.matcher("abc");
        p(m.matches());
        //上面的三行代碼可以用下面一行代碼代替
        p("abc".matches("[a-z]{3}"));
    }
    
    public static void p(Object o){
        System.out.println(o);
    }
} 
複製代碼

下面是打印結果

true
a****a
true
true

 現在通過一些實驗來說明正則表達式的匹配規則,這兒是Greedy方式

  .              任何字符

 a?             a一次或一次也沒有

 a*             a零次或多次

 a+            a一次或多次

 a{n}?      a恰好 n 次

 a{n,}?       a至少n次 

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

 

複製代碼
        //初步認識. * + ?
        p("a".matches("."));//true
        p("aa".matches("aa"));//true
        p("aaaa".matches("a*"));//true
        p("aaaa".matches("a+"));//true
        p("".matches("a*"));//true
        p("aaaa".matches("a?"));//false
        p("".matches("a?"));//true
        p("a".matches("a?"));//true
        p("1232435463685899".matches("\\d{3,100}"));//true
        p("192.168.0.aaa".matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"));//false
        p("192".matches("[0-2][0-9][0-9]"));//true
複製代碼

 

[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](減去)

 

複製代碼
        //範圍
        p("a".matches("[abc]"));//true
        p("a".matches("[^abc]"));//false
        p("A".matches("[a-zA-Z]"));//true
        p("A".matches("[a-z]|[A-Z]"));//true
        p("A".matches("[a-z[A-Z]]"));//true
        p("R".matches("[A-Z&&[RFG]]"));//true
複製代碼

 

\d                          數字:[0-9]

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

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

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

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

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

 

         //認識\s \w \d \
        p("\n\r\t".matches("\\s(4)"));//false
        p(" ".matches("\\S"));//false
        p("a_8 ".matches("\\w(3)"));//false
        p("abc888&^%".matches("[a-z]{1,3}\\d+[&^#%]+"));//true
        p("\\".matches("\\\\"));//true

 

 邊界匹配器

      ^                                          行的開頭

      $                                          行的結尾

      \b                                        單詞邊界

      \B                                        非單詞邊界

      \A                                        輸入的開頭

      \G                                       上一個匹配的結尾

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

      \z                                       輸入的結尾

 

複製代碼
        //邊界匹配
        p("hello sir".matches("^h.*"));//true
        p("hello sir".matches(".*ir$"));//true
        p("hello sir".matches("^h[a-z]{1,3}o\\b.*"));//true
        p("hellosir".matches("^h[a-z]{1,3}o\\b.*"));//false
        //空白行:一個或多個(空白並且非換行符)開頭,並以換行符結尾
        p(" \n".matches("^[\\s&&[^\\n]]*\\n$"));//true
複製代碼

 方法解析

matches():匹配整個字符串

find():匹配子字符串

lookingAt():永遠從整個字符串的開頭開始匹配

複製代碼
//email
        p("[email protected]".matches("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+"));//true
        
        //matches() find() lookingAt()
        Pattern p = Pattern.compile("\\d{3,5}");
        Matcher m = p.matcher("123-34345-234-00");
        
        //將整個"123-34345-234-00"用正則表達式引擎查找匹配,當到第一個"-"不匹配了,就停止,
        //但不會將不匹配的"-"吐出來
        p(m.matches());
        //將不匹配的"-"吐出來
        m.reset();
        
        //1:當前面有p(m.matches());查找子字符串從"...34345-234-00"開始
        //將會是第1,2兩個查到"34345"和"234" 後面2個查不到爲false
        //2:當前面有p(m.matches());和m.reset();查找子字符串從"123-34345-234-00"開始
        //將爲true,true,true,false
        p(m.find());
        p(m.start()+"---"+m.end());
        p(m.find());
        p(m.start()+"---"+m.end());
        p(m.find());
        p(m.start()+"---"+m.end());
        p(m.find());
        //要是沒找到就會報異常java.lang.IllegalStateException
        //p(m.start()+"---"+m.end());
        
        p(m.lookingAt());
        p(m.lookingAt());
        p(m.lookingAt());
        p(m.lookingAt());
複製代碼

字符串替換:下面這種方法對於字符串替換非常靈活

複製代碼
        //字符串替換
        //Pattern.CASE_INSENSITIVE大小寫不敏感
        Pattern p = Pattern.compile("java",Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher("java Java jAva ILoveJavA youHateJAVA adsdsfd");
        //存放字符串
        StringBuffer  buf = new StringBuffer();
        //計數奇偶數
        int i  = 0;
        while(m.find()){
            i++;
            if(i%2 == 0){
                m.appendReplacement(buf, "java");
            }else{
                m.appendReplacement(buf, "JAVA");
            }
        }
        //不加這句話,字符串adsdsfd將會被遺棄
        m.appendTail(buf);
        p(buf);
複製代碼

結果打印:

JAVA java JAVA ILovejava youHateJAVA adsdsfd

分組

 

複製代碼
        //group分組,用()分組
        Pattern p = Pattern.compile("(\\d{3,5})([a-z]{2})");
        String s = "123aa-34345bb-234cc-00";
        Matcher m = p.matcher(s);
        p(m.groupCount());//2組
        while(m.find()){
            p(m.group());//數字字母都有
            //p(m.group(1));//只有數字
            //p(m.group(2));//只有字母
        }
複製代碼

 

package com.inspur.regular;


public class Demo1_Regular {


/**
* @param args
*/
public static void main(String[] args) {
//demo1();
//demo2();
//demo3();
//demo4();
//demo5();
//demo6();
//demo7();
demo8();
}


public static void demo8() {
//電話號碼
String regex1 = "1[34578]\\d{9}";
String regex2 = "1[34578]\\d{4}(\\d)\\1{4}";
System.out.println("13812300000".matches(regex2));//true
System.out.println("15932166666".matches(regex2));//true
System.out.println("13812345678".matches(regex2));//false
}


public static void demo7() {
//疊詞
String regex = "(.)\\1+(.)\\2+";
System.out.println("快快樂樂".matches(regex));//true
System.out.println("高高興興".matches(regex));//true
System.out.println("快快快樂樂樂".matches(regex));//true

String regex2 = "(..)\\1";
System.out.println("樂呵樂呵".matches(regex2));//true
System.out.println("死啦死啦".matches(regex2));//true
}


public static void demo6() {
//5,密碼. 任意字符, 6-16位
String regex = ".{6,16}";
System.out.println("123456".matches(regex));//true
System.out.println("abcde".matches(regex));//false
System.out.println("1234567890987654".matches(regex));//true
System.out.println("12345678909876543".matches(regex));//false
}


public static void demo5() {
//4,用戶名. 字母數字下劃線10位以內, 必須是字母開頭
String regex = "[a-zA-Z]\\w{0,9}";
System.out.println("0abcde".matches(regex));//false
System.out.println("a".matches(regex));//true
System.out.println("abcdef12345".matches(regex));//false
}


public static void demo4() {
//3,Email   [email protected]
//          [email protected]
String regex = "[\\w-\\.]+@([\\w-]+\\.)+[a-z]{2,3}";
System.out.println("[email protected]".matches(regex));//false
System.out.println("[email protected]".matches(regex));//true
System.out.println("[email protected]".matches(regex));//true
System.out.println("[email protected]".matches(regex));//true
System.out.println("[email protected]".matches(regex));//true
}


public static void demo3() {
//2,手機號
String regex = "1[34578]\\d{9}";
System.out.println("13898765432".matches(regex));//true
System.out.println("01234567890".matches(regex));//false
System.out.println("16123456789".matches(regex));//false
System.out.println("159123456780".matches(regex));//false
}


public static void demo2() {
//1,1-6位字母或數字:
String regex = "[\\d[a-zA-Z]]{1,6}";
System.out.println("123456".matches(regex));//true
System.out.println("1".matches(regex));//true
System.out.println("abcd".matches(regex));//true
System.out.println("1a2b3c".matches(regex));//true
System.out.println("1a2b3c4d".matches(regex));//false
}


public static void demo1() {
//qq號碼
String regex = "[1-9]\\d{4,10}";
System.out.println("2553868".matches(regex));//true
System.out.println("012345".matches(regex));//false
System.out.println("12345678987".matches(regex));//true
}




}

 

二、正則表達式簡單使用

 

java正則表達式應用

 

三、其他網上資料

深入淺出之正則表達式(一)

深入淺出之正則表達式(二)

正則表達式30分鐘入門教程

JQuery 正則表達式實例



轉載自:http://www.cnblogs.com/ITtangtang/archive/2012/05/01/2477563.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章