Java Regex: matches(pattern, value) returns true but group() fails to match

You need to call find() before group():

String pattern = "([^-]*)-([\\D]*)([\\d]*)"; 
String value = "SSS-BB0000";
Matcher matcher = Pattern.compile(pattern).matcher(value); 
if (matcher.find()) {
  System.out.println(matcher.group()); // SSS-BB0000
  System.out.println(matcher.group(0)); // SSS-BB0000
  System.out.println(matcher.group(1)); // SSS
  System.out.println(matcher.group(2)); // BB
  System.out.println(matcher.group(3)); // 0000
}

When you invoke matcher(value), you are merely creating a Matcher object that will be able to match your value. In order to actually scan the input, you need to use find() or lookingAt():

References:

  • Matcher#find()

Tags:

Java

Regex