You will get this exception message when you are trying to use named groups in java regex validation or matching.
Root Cause of No match found Error in Regex Named Group Matching
Error log will show the message like below:
Exception in thread "main" java.lang.IllegalStateException: No match found at java.util.regex.Matcher.group(Unknown Source)
Solution
You are probably not using “matcher.matches()” before fetching the named group from matcher. You should do the complete oprtation like below:
List<String> dates = new ArrayList<String>(); dates.add("02/31/2011"); //Invalid date dates.add("02/27/2011"); //Valid date String regex = "^(?<month>[0-3]?[0-9])/(?<day>[0-3]?[0-9])/(?<year>(?:[0-9]{2})?[0-9]{2})$"; Pattern pattern = Pattern.compile(regex); for (String date : dates) { Matcher matcher = pattern.matcher(date); //This is the root cause of error. Don't forget to do this !! matcher.matches(); //Get date parts here String day = matcher.group(2); String month = matcher.group(1); String year = matcher.group(3); String formattedDate = month + "/" + day + "/" + year; System.out.println("Date to check : " + formattedDate); }
This will solve your error in most of the cases.
Happy Learning !!
Leave a Reply