程式扎記: [ Java 常見問題 ] Reference to previous matched groups within a regex

標籤

2015年6月8日 星期一

[ Java 常見問題 ] Reference to previous matched groups within a regex

Source From Here 
Question 
Is there a way in Java to refer to previous matched groups within the regex? 

How-To 
Sample code as below: 
  1. package howto;  
  2.   
  3. import java.util.regex.Matcher;  
  4. import java.util.regex.Pattern;  
  5.   
  6. public class Test {  
  7.   
  8.     public static void main(String[] args) throws Exception  
  9.     {  
  10.         String str = "A123 A123 A123 A123";  
  11.         // The outermost () is group1; So "(\\w\\d\\d\\d)" is group2.  
  12.         Pattern ptn = Pattern.compile("((\\w\\d\\d\\d)(\\s+\\2)*)");  
  13.         Matcher mth = ptn.matcher(str);  
  14.         if(mth.find())  
  15.         {  
  16.             for(int i=0; i
  17.             {  
  18.                 System.out.printf("G%d: '%s'\n", i+1, mth.group(i+1));  
  19.             }  
  20.         }  
  21.         else  
  22.         {  
  23.             System.err.printf("Miss!\n");  
  24.         }  
  25.     }  
  26. }  
Execution result: 
G1: 'A123 A123 A123 A123'
G2: 'A123'
G3: ' A123'

沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!