Pattern/ Matcher Java, non zero group count but error retrieving?
java, regex
Solution
`groupCount` just tells you how many groups are defined in the regular expression. If you want to actually access a result, you have to perform a match first!
if (matcher1.find()) {
System.out.println("matcher1.group(0) = " (matcher1.group(0)).toString());
} else {
System.out.println("No match.");
}
Also `.` is a special character in regex, you probably wanted `\\.`?
Problem
My `matcher.groupCount()` is giving me 4 but when I use `matcher.group(0)`, ..., `matcher.group(0)`, it gives me an error. Following is my code: ``` 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()); ``` Console: ``` 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) ``` the line number is pointing to ``` System.out.println("matcher1.group(0) = " (matcher1.group(0)).toString()); ```