java中正則表達式以及Pattern和Matcher

正則匹配

// 反斜槓
/t 間隔 ('/u0009')
/n 換行 ('/u000A')
/r 回車 ('/u000D')
/d 數字 等價於[0-9]
/D 非數字 等價於[^0-9]
/s 空白符號 [/t/n/x0B/f/r]
/S 非空白符號 [^/t/n/x0B/f/r]
/w 單獨字符 [a-zA-Z_0-9]
/W 非單獨字符 [^a-zA-Z_0-9]
/f 換頁符
/e Escape
/b 一個單詞的邊界
/B 一個非單詞的邊界
/G 前一個匹配的結束
^爲限制開頭
^java     條件限制爲以Java爲開頭字符
$爲限制結尾
java$     條件限制爲以java爲結尾字符
.  條件限制除/n以外任意一個單獨字符
java..     條件限制爲java後除換行外任意兩個字符
加入特定限制條件「[]」
[a-z]     條件限制在小寫a to z範圍中一個字符
[A-Z]     條件限制在大寫A to Z範圍中一個字符
[a-zA-Z] 條件限制在小寫a to z或大寫A to Z範圍中一個字符
[0-9]     條件限制在小寫0 to 9範圍中一個字符
[0-9a-z] 條件限制在小寫0 to 9或a to z範圍中一個字符
[0-9[a-z]] 條件限制在小寫0 to 9或a to z範圍中一個字符(交集)
[]中加入^後加再次限制條件「[^]」
[^a-z]     條件限制在非小寫a to z範圍中一個字符
[^A-Z]     條件限制在非大寫A to Z範圍中一個字符
[^a-zA-Z] 條件限制在非小寫a to z或大寫A to Z範圍中一個字符
[^0-9]     條件限制在非小寫0 to 9範圍中一個字符
[^0-9a-z] 條件限制在非小寫0 to 9或a to z範圍中一個字符
[^0-9[a-z]] 條件限制在非小寫0 to 9或a to z範圍中一個字符(交集)
在限制條件爲特定字符出現0次以上時,可以使用「*」
J*     0個以上J
.*     0個以上任意字符
J.*D     J與D之間0個以上任意字符
在限制條件爲特定字符出現1次以上時,可以使用「+」
J+     1個以上J
.+     1個以上任意字符
J.+D     J與D之間1個以上任意字符
在限制條件爲特定字符出現有0或1次以上時,可以使用「?」
JA?     J或者JA出現
限制爲連續出現指定次數字符「{a}」
J{2}     JJ
J{3}     JJJ
文字a個以上,並且「{a,}」
J{3,}     JJJ,JJJJ,JJJJJ,???(3次以上J並存)
文字個以上,b個以下「{a,b}」
J{3,5}     JJJ或JJJJ或JJJJJ
兩者取一「|」
J|A     J或A
Java|Hello     Java或Hello
 「()」中規定一個組合類型
比如,我查詢<a href=/"index.html/">index</a>中<a href></a>間的數據,可寫作<a.*href=/".*/">(.+?)</a>
在使用Pattern.compile函數時,可以加入控制正則表達式的匹配行爲的參數:
Pattern Pattern.compile(String regex, int flag)

Pattern類和Matcher類

Java正則表達式通過java.util.regex包下的Pattern類與Matcher類實現(建議在閱讀本文時,打開Java API文檔,當介紹到哪個方法時,查看java API中的方法說明,效果會更佳). 
Pattern類用於創建一個正則表達式,也可以說創建一個匹配模式,它的構造方法是私有的,不可以直接創建,但可以通過Pattern.complie(String regex)簡單工廠方法創建一個正則表達式, 
Java代碼示例: 
Pattern p=Pattern.compile("\\w+"); 
p.pattern();//返回 \w+ 


pattern() 返回正則表達式的字符串形式,其實就是返回Pattern.complile(String regex)的regex參數 

1.Pattern.split(CharSequence input) 
Pattern有一個split(CharSequence input)方法,用於分隔字符串,並返回一個String[]
Java代碼示例: 
Pattern p=Pattern.compile("\\d+"); 
String[] str=p.split("我的QQ是:456456我的電話是:0532214我的郵箱是:[email protected]"); 


結果:str[0]="我的QQ是:" str[1]="我的電話是:" str[2]="我的郵箱是:[email protected]

2.Pattern.matcher(String regex,CharSequence input)是一個靜態方法,用於快速匹配字符串,該方法適合用於只匹配一次,且匹配全部字符串. 
Java代碼示例: 

Pattern.matches("\\d+","2223");//返回true 
Pattern.matches("\\d+","2223aa");//返回false,需要匹配到所有字符串才能返回true,這裏aa不能匹配到 
Pattern.matches("\\d+","22bb23");//返回false,需要匹配到所有字符串才能返回true,這裏bb不能匹配到 
3.Pattern.matcher(CharSequence input) 
說了這麼多,終於輪到Matcher類登場了,Pattern.matcher(CharSequence input)返回一個Matcher對象. 
Matcher類的構造方法也是私有的,不能隨意創建,只能通過Pattern.matcher(CharSequence input)方法得到該類的實例. 
Pattern類只能做一些簡單的匹配操作,要想得到更強更便捷的正則匹配操作,那就需要將Pattern與Matcher一起合作.Matcher類提供了對正則表達式的分組支持,以及對正則表達式的多次匹配支持. 
Java代碼示例: 
Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("22bb23"); 
m.pattern();//返回p 也就是返回該Matcher對象是由哪個Pattern對象的創建的 

4.Matcher.matches()/ Matcher.lookingAt()/ Matcher.find() 
Matcher類提供三個匹配操作方法,三個方法均返回boolean類型,當匹配到時返回true,沒匹配到則返回false 


matches()對整個字符串進行匹配,只有整個字符串都匹配了才返回true 
Java代碼示例: 

Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("22bb23"); 
m.matches();//返回false,因爲bb不能被\d+匹配,導致整個字符串匹配未成功. 
Matcher m2=p.matcher("2223"); 
m2.matches();//返回true,因爲\d+匹配到了整個字符串 
我們現在回頭看一下Pattern.matcher(String regex,CharSequence input),它與下面這段代碼等價 
Pattern.compile(regex).matcher(input).matches() 


lookingAt()對前面的字符串進行匹配,只有匹配到的字符串在最前面才返回true 
Java代碼示例: 
Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("22bb23"); 
m.lookingAt();//返回true,因爲\d+匹配到了前面的22 
Matcher m2=p.matcher("aa2223"); 
m2.lookingAt();//返回false,因爲\d+不能匹配前面的aa 
find()對字符串進行匹配,匹配到的字符串可以在任何位置. 
Java代碼示例: 
Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("22bb23"); 
m.find();//返回true 
Matcher m2=p.matcher("aa2223"); 
m2.find();//返回true 
Matcher m3=p.matcher("aa2223bb"); 
m3.find();//返回true 
Matcher m4=p.matcher("aabb"); 
m4.find();//返回false 
5.Mathcer.start()/ Matcher.end()/ Matcher.group() 
當使用matches(),lookingAt(),find()執行匹配操作後,就可以利用以上三個方法得到更詳細的信息. 
start()返回匹配到的子字符串在字符串中的索引位置. 
end()返回匹配到的子字符串的最後一個字符在字符串中的索引位置. 
group()返回匹配到的子字符串 
Java代碼示例:
Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("aaa2223bb"); 
m.find();//匹配2223 
m.start();//返回3 
m.end();//返回7,返回的是2223後的索引號 
m.group();//返回2223 

Mathcer m2=m.matcher("2223bb"); 
m.lookingAt();   //匹配2223 
m.start();   //返回0,由於lookingAt()只能匹配前面的字符串,所以當使用lookingAt()匹配時,start()方法總是返回0 
m.end();   //返回4 
m.group();   //返回2223 

Matcher m3=m.matcher("2223bb"); 
m.matches();   //匹配整個字符串 
m.start();   //返回0,原因相信大家也清楚了 
m.end();   //返回6,原因相信大家也清楚了,因爲matches()需要匹配所有字符串 
m.group();   //返回2223bb 
說了這麼多,相信大家都明白了以上幾個方法的使用,該說說正則表達式的分組在java中是怎麼使用的. 
start(),end(),group()均有一個重載方法它們是start(int i),end(int i),group(int i)專用於分組操作,Mathcer類還有一個groupCount()用於返回有多少組. 
Java代碼示例: 
Pattern p=Pattern.compile("([a-z]+)(\\d+)"); 
Matcher m=p.matcher("aaa2223bb"); 
m.find();   //匹配aaa2223 
m.groupCount();   //返回2,因爲有2組 
m.start(1);   //返回0 返回第一組匹配到的子字符串在字符串中的索引號 
m.start(2);   //返回3 
m.end(1);   //返回3 返回第一組匹配到的子字符串的最後一個字符在字符串中的索引位置. 
m.end(2);   //返回7 
m.group(1);   //返回aaa,返回第一組匹配到的子字符串 
m.group(2);   //返回2223,返回第二組匹配到的子字符串 
現在我們使用一下稍微高級點的正則匹配操作,例如有一段文本,裏面有很多數字,而且這些數字是分開的,我們現在要將文本中所有數字都取出來,利用java的正則操作是那麼的簡單. 
Java代碼示例: 
Pattern p=Pattern.compile("\\d+"); 
Matcher m=p.matcher("我的QQ是:456456 我的電話是:0532214 我的郵箱是:[email protected]"); 
while(m.find()) { 
     System.out.println(m.group()); 
} 

輸出: 
456456 
0532214 
123 

如將以上while()循環替換成 
while(m.find()) { 
     System.out.println(m.group()); 
     System.out.print("start:"+m.start()); 
     System.out.println(" end:"+m.end()); 
} 
則輸出: 
456456 
start:6 end:12 
0532214 
start:19 end:26 
123 
start:36 end:39 




加上一個自己寫的代碼例子:

不用看,只是自己做一些記錄:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**學習正則表達式
 * Created by Administrator on 2017/5/28.
 */
public class PatAndMac {
    public static void main(String []args){
        String a = "將來的我比現在好";
        System.out.println(a.matches("將來的"));
        String string = "192.168.10.1";
        String rule = "\\d{1,3}\\.\\d{1,3}.\\d{1,3}.\\d{1,3}";
        System.out.println("192.168.10.1".matches("\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}"));
        Pattern.matches("192.168.10.1","\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}");
        System.out.println("aa".matches("aa?"));//?表示0-1次
        System.out.println("aar".matches("aar+"));//+表示1-N次
        System.out.println("".matches("a*"));//*表示出現過0-N次
        System.out.println("w".matches("."));
        System.out.println("qasugg135".matches("[a-z]{6}[0-9]{3}"));
        System.out.println("[email protected]".matches("[0-9]+@\\w+.(com|cn|org|io)"));
        System.out.println("hello".matches("^h.*o$"));
        Pattern pattern = Pattern.compile(rule);
        Matcher matcher = pattern.matcher(string);
        System.out.println("全字符串匹配--->"+matcher.matches());
        pattern = Pattern.compile("[a-z]+");
        matcher = pattern.matcher("ewqgu34");//12ewqgu34就返回false
        System.out.println("前面的匹配--->"+matcher.lookingAt());
        pattern = Pattern.compile("\\w+");
        matcher = pattern.matcher("@#!##_");
        System.out.println("任意位子的匹配:只要出現就好--->"+matcher.find());
        pattern = Pattern.compile("\\d+");
        matcher = pattern.matcher("436vgf12w1135");
        if(matcher.find()){
            System.out.println("start---->"+matcher.start());
            System.out.println("end---->"+matcher.end());
            System.out.println("group---->"+matcher.group());
        }else {
            System.out.println("不匹配呀");
        }
        if(matcher.lookingAt()){
            System.out.println("start---->"+matcher.start());
            System.out.println("end---->"+matcher.end());
            System.out.println("group---->"+matcher.group());
        }else {
            System.out.println("不匹配呀");
        }
        if(matcher.matches()){
            System.out.println("start---->"+matcher.start());
            System.out.println("end---->"+matcher.end());
            System.out.println("group---->"+matcher.group());
        }else {
            System.out.println("不匹配呀");
        }

        pattern = Pattern.compile("\\d+");
        matcher = pattern.matcher("我的QQ是:456456 我的電話是:0532214 我的郵箱是:[email protected]");
        while(matcher.find()){
            System.out.println("find是可以循環的~~~~~~~");
            System.out.println("start:"+matcher.start()+"end:"+ matcher.end()+"group:"+ matcher.group());
        }
        pattern = Pattern.compile("[a-z]+\\d+");
        matcher = pattern.matcher("gg12415hh");
       /* matcher.find();
        System.out.println(matcher.start(1));
        System.out.println(matcher.end(1));
        System.out.println(matcher.group(1));
        System.out.println(matcher.group(2));
        System.out.println(matcher.start(2));
        System.out.println(matcher.end(2));*/
       /* matcher.find();
        System.out.println("數目:"+matcher.groupCount()+"呀:---->"+matcher.find()+"---"+matcher.find());*/
        while(matcher.find()){
            System.out.println(matcher.groupCount());
            System.out.println("?"+matcher.group());
        }

        pattern = Pattern.compile("aoy*");
        matcher = pattern.matcher("aoyyyyyyys5s");
        System.out.println(matcher.lookingAt());
        matcher = pattern.matcher("aoy");
        System.out.println(matcher.matches());
        /*pattern = Pattern.compile("(http://|https://){1}[\\w]+");//(http://|https://){1}[\w.:]+"
        matcher = pattern.matcher("dsdsds<http://www.baidu.com_1>fdf");
        StringBuffer buffer = new StringBuffer();
        while(matcher.find()){
            buffer.append(matcher.group());
            System.out.println(buffer.toString());
        }*/

        /*pattern = Pattern.compile("\"(.+?)\"");
        matcher = pattern.matcher("<a href=\"index.html\">主頁</a>");
        if(matcher.find())
            System.out.println(matcher.group(1));*/
        PatAndMac pam = new PatAndMac();
        pattern = Pattern.compile("\\{\\}");
        String []s = {"手機號碼"};
//        pam.replaceContent(pattern,"參數中的\"{}\"不能爲空",s);
//        System.out.println(s);

        String param = "一個數字加上N個字母";
        pattern = Pattern.compile("[0-9]{1}[a-zA-Z]+");
        pam.rep(pattern,"2ag6f227574_iyf3uo你好呀",param);
    }
    private static String replaceContent(Pattern pattern,String content, String... params){
        Matcher matcher = pattern.matcher(content);
        StringBuffer sb = new StringBuffer();
        Integer idx = 0;
        while(matcher.find()) {
            if(params != null && idx < params.length) {
                System.out.println("true次數+1");
                String pm = params[idx++];
                matcher.appendReplacement(sb, (pm == null) ? "null" : pm);
            }else{
                System.out.println("false次數+1");
                matcher.appendReplacement(sb, "null");
            }
        }
        System.out.println(sb.toString());
        matcher.appendTail(sb);
        System.out.println(sb.toString());
        return sb.toString();
    }

    private static void rep(Pattern pattern,String context,String param){
        Matcher matcher = pattern.matcher(context);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()){
            matcher.appendReplacement(sb,param);
            System.out.println(sb.toString());
        }
        matcher.appendTail(sb);
        System.out.println(sb.toString());
    }



}
輸出:
false
true
true
true
true
true
true
true
true
全字符串匹配--->true
前面的匹配--->true
任意位子的匹配:只要出現就好--->true
start---->0
end---->3
group---->436
start---->0
end---->3
group---->436
不匹配呀
find是可以循環的~~~~~~~
start:6end:12group:456456
find是可以循環的~~~~~~~
start:19end:26group:0532214
find是可以循環的~~~~~~~
start:36end:39group:123
0
?gg12415
true
true
一個數字加上N個字母
一個數字加上N個字母一個數字加上N個字母
一個數字加上N個字母一個數字加上N個字母227574_iyf一個數字加上N個字母
一個數字加上N個字母一個數字加上N個字母227574_iyf一個數字加上N個字母你好呀

發佈了80 篇原創文章 · 獲贊 25 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章