1. 程式人生 > >正則表示式之前後查詢(Java版) 例項

正則表示式之前後查詢(Java版) 例項

 參考部落格:http://blog.csdn.net/libingxin/article/details/7840998

?= 正向向前查詢:出現在指定項之的字元序列不會被正則表示式引擎返回
?<= 正向向後查詢:出現在指定項之的字元序列不會被正則表示式引擎返回
?<! 負向向後查詢:不出現在指定項之的字元序列不會被正則表示式引擎返回
?! 負向向前查詢:不出現在指定項之的字元序列不會被正則表示式引擎返回

記憶:= 為正向 有<表示向後,沒有<表示向前, !表示負向

@Test
    public void look(){
        String str="\\http://www.baidu.com"
; System.out.println("?= 正向向前查詢"); String prex=".+(?=:)"; Pattern p=Pattern.compile(prex); Matcher m=p.matcher(str); while(m.find()){ System.out.println(m.group()); //\http } /**可以看到字表達式(?=:)匹配:, 但被匹配的:沒有出現在最終的匹配結果裡, 我們用?=向正則表示式引擎表明:只要找到:就行了, 不要把它包括在最終結果裡。用術語來說,就是”不消費”它。*/
System.out.println("?<= 正向向後查詢 "); String str2="d23.90 d12.32 d12.34 33.33"; String prex2="(?<=d)[0-9].+"; // 23.90 d12.32 d12.34 33.33 //String prex2="(?<=d)[0-9].+?"; //result :23 12 12 p=Pattern.compile(prex2); m=p.matcher(str2); while
(m.find()){ System.out.println(m.group()); } System.out.println("?! 負向前查詢 "); String str3="the book cost and the phone cost 1000 2d"; String prex3="\\d+(?!d)"; //1000 /**String prex3="\\d+(?=d)"; //result :2 ?=d 表示d這個字母遇見了就行了 * 解析:是以空格分隔解析的,所以2d 才滿足這個正則表示式 * 也就輸出2了 */ p=Pattern.compile(prex3); m=p.matcher(str3); while(m.find()){ System.out.println(m.group()); } System.out.println("?<!負向後查詢 "); String str4="the d2 wow 30"; String prex4="(?<!d)\\d+"; //String prex4= p=Pattern.compile(prex4); m=p.matcher(str4); while(m.find()){ System.out.println(m.group()); } System.out.println("向前查詢向後查詢混合使用 "); String str5="(title)ben hah wowo(/title)"; String prex5="(?<=(title)).*(?=(/title))"; //result :)ben hah wowo( /** * 我理解的是result沒有那兩個半括號 但是就是有 這是為什麼 */ //String prex5= p=Pattern.compile(prex5); m=p.matcher(str5); while(m.find()){ System.out.println(m.group()); } }