2016-07-29 24 views
1

在Java中,我想使用正則表達式以「MM/DD/YYYY」格式解析日期字符串。我試圖用圓括號製作捕獲組,但似乎並不奏效。它只返回整個匹配的字符串 - 不是「MM」,「DD」和「YYYY」組件。Java正則表達式不會返回捕獲組

public static void main(String[] args) { 
    Pattern p1=Pattern.compile("(\\d{2})/(\\d{2})/(\\d{4})"); 
    Matcher m1=p1.matcher("04/30/1999"); 

    // Throws IllegalStateException: "No match found": 
    //System.out.println("Group 0: "+m1.group(0)); 

    // Runs only once and prints "Found: 04/30/1999". 
    while (m1.find()){ 
     System.out.println("Found: "+m1.group()); 
    } 
    // Wanted 3 lines: "Found: 04", "Found: 30", "Found: 1999" 
} 

的「group」功能,需要一個參數(m1.group(x))似乎並沒有在所有的工作,因爲它返回一個例外,不管我給什麼指標吧。循環播放find()只返回單個整場比賽「04/30/1999」。正則表達式中的括號似乎完全沒用!

這是很容易在Perl做:

my $date = "04/30/1999"; 
my ($month,$day,$year) = $date =~ m/(\d{2})\/(\d{2})\/(\d{4})/; 
print "Month: ",$month,", day: ",$day,", year: ",$year; 
# Prints: 
#  Month: 04, day: 30, year: 1999 

我缺少什麼? Java正則表達式是否無法解析像Perl中的捕獲組?

回答

3

呼叫m1.find()第一,然後用m1.group(N)

matcher.group()matcher.group(0)返回整個匹配的文本。
matcher.group(1)返回第一組匹配的文本。
matcher.group(2)返回第二組匹配的文本。
...

代碼

Pattern p1=Pattern.compile("(\\d{2})/(\\d{2})/(\\d{4})"); 
Matcher m1=p1.matcher("04/30/1999"); 

if (m1.find()){ //you can use a while loop to get all match results 
    System.out.println("Month: "+m1.group(1)+" Day: "+m1.group(2)+" Year: "+m1.group(3)); 
} 

結果

Month: 04 Day: 30 Year: 1999 

ideone demo