2016-08-18 125 views
0

我無法理解組的輸出,它如何考慮模式中的每個pativehesis,並將其與變量'line'等同。請解釋Java正則表達式組

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

public class RegexTut3 { 

    public static void main(String args[]) { 
    String line = "This order was placed for QT3000! OK?"; 
    String pattern = "(.*)(\\d+)(.*)"; 

    // Create a Pattern object 
    Pattern r = Pattern.compile(pattern); 

    // Now create matcher object. 
    Matcher m = r.matcher(line); 

    if (m.find()) { 
     System.out.println("Found value: " + m.group(0)); 
     System.out.println("Found value: " + m.group(1)); 
     System.out.println("Found value: " + m.group(2)); 
    } else { 
     System.out.println("NO MATCH"); 
    } 
    } 
} 
+0

引用自己... [這裏](http://stackoverflow.com/questions/17969436/java-regex-capturing - 基團/ 17969620#17969620)。 – Mena

+0

正則表達式只抓取除最後一位數字之外的換行符(並放入組1)中的字符數,然後將最後一位數字放入組2中,其餘行放入組3中。貪婪的量詞和回溯。 –

回答

-1

模式"(.*)(\\d+)(.*)"手段:

(.*) - Consume anything and store it in group 0 
(\\d+) - Consume a number and store it in the next group, i.e. group 2 
(.*) - Consume anything and store it in the next group 

這樣的格局將查找字符串的數量和組0之前它存儲所有信息,在組1,其餘數2組中的字符串。

-1

m.group(0)總是匹配整個模式。你的比賽真正開始於1,不是0

m.group(0): matches the whole pattern 
m.group(1): first parenthesis 
m.group(2): second set of parenthesis 
m.group(3): third set 

編輯:作出修正