I have an odd problem with a regular expression in Java. I tested my Regex and my value here and it works. It says there are 3 groups (correct) the match for the first group
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()
:
I faced the same issue. Was calling matcher.group(1)
WITHOUT checking matcher.find()
. Adding if check for matcher.find()
solved the problem.