java 正則表達式獲取匹配和非獲取匹配


 1 package test1;
 2 
 3 import java.util.regex.Matcher;
 4 import java.util.regex.Pattern;
 5 
 6 public class TestExp {
 7     /**
 8      * 
 9      * 在使用正則表達式的時候,我們經常會使用()把某個部分括起來,稱為一個子模式。 子模式有Capturing和Non-Capturing兩種情況。
10      * Capturing指獲取匹配 :
11      * 是指系統會在幕后將所有的子模式匹配結果保存起來,供我們查找或者替換。如后向引用(在表達式的后面應用前面匹配的子字符串)的使用;
12      * Non-Capturing指非獲取匹配 :
13      * 這時系統並不會保存子模式的匹配結果,子模式的匹配更多的只是作為一種限制條件使用,如正向預查,反向預查,負正向預查,負反向預查等。
14      * 
15      * 在Java中可以使用非獲取匹配作為篩選子字符串的條件。例如 想獲得“hello world !”中的“hello world ”
16      * ,注意,不要感嘆號。 就可以再匹配感嘆號時使用非獲取的正則表達式。("hello world (?=!)")
17      * 
18      * Java中后向引用的使用:
19      * "abc def".replaceFirst("(\\w+)\\s+(\\w+)", "$2 $1"); //結果為def abc 
20      * "abc def aaa bbb".replaceAll("(\\w+)\\s+(\\w+)", "$2 $1"); //結果是 def abc bbb aaa
21      * 
22      * 使用$x替換字符中子字符串。
23      * 
24      * */
25     public static void main(String[] args) {
26         /** groupcount 的下標是從0開始的,也就是說如果獲取一個匹配項,那么該值為0 */
27         /** 正向肯定預查 */
28         /**
29          * 目的: 查找元字符中符合“win ”格式的子字符串,而且該字符串后面緊跟一個“7”字符串。
30          * 
31          * */
32         /*
33          * Pattern ptn = Pattern.compile("win (?=7)",Pattern.UNICODE_CASE) ;
34          * Matcher m = ptn.matcher("win 7") ; System.out.println("groupcount: "
35          * + m.groupCount()); while(m.find()){ System.out.println(m.group()); }
36          */
37         /** 正向否定預查 */
38         /**
39          * 目的: 查找元字符中符合“win ”格式的子字符串,而且該字符串后面沒有跟一個“7”字符串。
40          * 
41          * */
42         /*
43          * Pattern ptn = Pattern.compile("win (?!7)",Pattern.UNICODE_CASE) ;
44          * Matcher m = ptn.matcher("win 8") ; while(m.find()){
45          * System.out.println(m.group()); }
46          */
47         /** 反向肯定預查 */
48         /**
49          * 目的:查找元字符串中符合“win”的子字符串,而且在該字符串前面還跟着“7”字符串。 獲取的是win,因為7是非獲取的。
50          * 
51          * */
52         /*
53          * Pattern ptn = Pattern.compile("(?<=7)win",Pattern.UNICODE_CASE) ;
54          * Matcher m = ptn.matcher("7win") ; while(m.find()){
55          * System.out.println(m.group()); }
56          */
57         /** 反向否定預查 */
58         /**
59          * 目的:查找元字符串中符合“win”的子字符串,而且在該字符串前面不跟“7”字符串。
60          * 
61          */
62         /*
63          * Pattern ptn = Pattern.compile("(?<!7)win",Pattern.UNICODE_CASE) ;
64          * Matcher m = ptn.matcher("8win") ; while(m.find()){
65          * System.out.println(m.group()); }
66          */
67     }
68 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM