2014-01-08 26 views
4

我的matcher.groupCount()給了我4個,但是當我使用,,...,matcher.group(0)時,它給了我一個錯誤。模式/匹配器Java,非零組計數但錯誤檢索?

以下是我的代碼:

Pattern pattern = Pattern.compile("([0-9]+).([0-9]+).([0-9]+).([0-9]+)"); 
Matcher matcher1, matcher2; 

GeoIP[0][0] = (GeoIP[0][0]).trim(); 
GeoIP[0][1] = (GeoIP[0][1]).trim(); 

System.out.println(GeoIP[0][0]); 
System.out.println(GeoIP[0][1]); 

matcher1 = pattern.matcher(GeoIP[0][0]); 
matcher2 = pattern.matcher(GeoIP[0][1]); 

System.out.println("matcher1.groupCount() = " + matcher1.groupCount()); 
System.out.println("matcher2.groupCount() = " + matcher2.groupCount()); 

System.out.println("matcher1.group(0) = " (matcher1.group(0)).toString()); 

控制檯:

Exception in thread "main" 1.0.0.0 
1.0.0.255 
matcher1.groupCount() = 4 
matcher2.groupCount() = 4 

java.lang.IllegalStateException: No match found 
    at java.util.regex.Matcher.group(Unknown Source) 
    at filename.main(filename.java:linenumber) 

行號指向

System.out.println("matcher1.group(0) = " (matcher1.group(0)).toString()); 

回答

7

groupCount只是告訴你有多少組在常規定義表達。如果您想實際訪問結果,您必須先執行匹配!

if (matcher1.find()) { 
    System.out.println("matcher1.group(0) = " (matcher1.group(0)).toString()); 
    } else { 
    System.out.println("No match."); 
    } 

而且.是在正則表達式的特殊字符,你可能想\\.

+0

YESSSS!非常感謝!!!! <3 – FailedMathematician

1

如果我理解正確,您需要訪問創建IP地址的四個字節。您可以嘗試使用匹配IP地址的正則表達式,然後拆分找到的字符串,而不是使用組。

String GeoIPs = "192.168.1.21, 10.16.254.1, 233.255.255.255"; 
Pattern pattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); 
Matcher matcher; 

matcher = pattern.matcher(GeoIPs); 

while (matcher.find()) { 
    String match = matcher.group(); 
    String[] ipParts = match.split("\\."); 
    for (String part : ipParts) { 
     System.out.print(part + "\t"); 
    } 
    System.out.println(); 
} 

有關於知識產權提取Java的正則表達式的一些答案: Extract ip addresses from Strings using regexregex ip address from string