AsfK
AsfK

Reputation: 3476

Matcher find a pattern but throw No match available on `start` method

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 exception.

Upvotes: 0

Views: 719

Answers (2)

anubhava
anubhava

Reputation: 785316

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 " 

Upvotes: 4

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59996

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"
}

Upvotes: 3

Related Questions