2017-06-03 43 views
8

Matcher.group() kullanarak tüm dizeleri bir dize yazdırmaya çalıştığım kodun altında çalışıyorum. Grup yok 2 İstisna: Yukarıdaki kodMatcher.group neden IndexOutOfOzBoundsException Exception atıyor

public static void main(String[] args) { 
     String s = "foo\r\nbar\r\nfoo" 
       + "foo, bar\r\nak = " 
       + "foo, bar\r\nak = " 
       + "bar, bar\r\nak = " 
       + "blr05\r\nsdfsdkfhsklfh"; 
     //System.out.println(s); 
     Matcher matcher = Pattern.compile("^ak\\s*=\\s*(\\w+)", Pattern.MULTILINE) 
       .matcher(s); 
     matcher.find(); 
     // This one works 
     System.out.println("first match " + matcher.group(1)); 
     // Below 2 lines throws IndexOutOfBoundsException 
     System.out.println("second match " + matcher.group(2)); 
     System.out.println("third match " + matcher.group(3)); 

    } 

iplik "ana" java.lang.IndexOutOfBoundsException içinde İstisna atar.

Bu yüzden sorum, Matcher.group()'un nasıl çalıştığını ve 3 eşleşen dizeye sahip olduğunuzu gördüğünüz gibi, group() kullanarak hepsini nasıl yazdırabilirim.

^ak\\s*=\\s*(\\w+) 
//   ^----^----------this is the only group 

yerine örneğin bir döngü kullanmak zorunda:

+0

"Matcher" ın ne tuttuğunu, "group" ve "find" ın nasıl etkileşimde bulunduğunu incelemek için bir breakpoint ayarlamak isteyebilirsiniz. – luk2302

+0

@ luk2302, debugger kullanmıştım, ancak 'group' ve' find 'un nasıl olduğunu bilmiyordum 'interaktif, –

cevap

İlgili konular