Tag Archives: not match

[Solved] java.lang.IllegalStateException: No match found : Regular Expression

java.lang.IllegalStateException is most common Runtime Exception and Unchecked Exception . It throws by JVM when trying to access object methods which are not allowed on certain cases.

In below example matcher.group(1) throwing IllegalStateException as “not match” . In below case as java.lang.Regex first we should call to matcher.find() method to get match in text for specific regular expression then based on matcher.group() we can get match text.

package com.test.exceptions;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpressionTest {

	public static void main(String[] args) {
		String text = "Facing Issues on IT";
		Pattern pattern = Pattern.compile("\\w");
		Matcher matcher = pattern.matcher(text);
		if (matcher != null) {
			System.out.println(matcher.group(1));//Exception on this point
			System.out.println("Match Count :" + matcher.groupCount() +matcher.find());
		}
	}
}

Output

Exception in thread "main" java.lang.IllegalStateException: No match found
	at java.util.regex.Matcher.group(Unknown Source)
	at com.test.exceptions.RegularExpressionTest.main(RegularExpressionTest.java:13)

Solution 

In below code match.find() not called before matcher.group(1) that’s why throwing IllegalStateException.

Summary

  • Explain about IllegalStateException and Example
  • For Regular Expression in java.lanag.Regex what need to take care.
  • How to solve it.

 

Advertisements