Home » Java » java – Matcher find a pattern but throw No match available on `start` method-Exceptionshub

java – Matcher find a pattern but throw No match available on `start` method-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Actaully I want to get the a sub string of the text after the regex, therefore I check if it exist with find, then I try to get start / end / group but java.lang.IllegalStateException: No match available is thrown.

String text = "Hello bob, remind me to do a lot of things today";
pattern = Pattern.compile("remind.*.to.");
// Looking for "remind <anyWord> to "
if (pattern.matcher(text).find())
{
    pattern.matcher(text).group();
}

The regex is found, therefore I in the condition, but start() (/any other int method) throw an excption..

Will be glad to understand…
Thanks!

How to&Answers:

Problem is that you’re using pattern.matcher(text) again and that creates another Matcher instance and when you call start() on a new instance it throws exception since find or matches or lookingAt has not been called before.

You may use it like this:

String text = "Hello bob, remind me to do a lot of things today";
final Pattern pattern = Pattern.compile("remind.*\hto\h");
Matcher m = pattern.matcher(text); // create it only once
// Looking for "remind <anyWord> to "
if (m.find()) {
    System.err.println( "Start: " + m.start() + ", match: " + m.group() );
}

Also note changes in your regex. \h matches a horizontal whitespace whereas .to. will match any character before and after to hence your regex will match:

"remind me to do a lot of things tod"

instead of intended:

"remind me to do " 

Answer:

You have to call pattern.matcher(text) one time, to do this, just create a Matcher like so:

Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
    String result = matcher.group();
    //output: "remind me to do a lot of things tod"
}