David
David

Reputation: 14963

Why does a Mattcher throw an exception after a successful find

I'm trying to write a loop that will find all the instances of "${arbitraryTextHere}" in an input string. E.g:

someText${findMe}moreText${findMeToo}EvenMoreText${DontForgetMe}

Here is my code:

    Pattern placeholderPattern = Pattern.compile("\\$\\{[\\w|\\d]+\\}");
    Matcher placeholderMatcher = placeholderPattern.matcher(templateString);

    int workingIndex = 0;
    while(placeholderMatcher.find()){
        workingIndex = placeholderMatcher.start();
    }

Note: The templateString I'm testing this out with is S"omeString ${someProp}"

The strange thing is that .find() has to return true in order to get inside the loop, but then .start() throws an IllegalStateException. The reason why this is so strange is that .start() only throws an IllegalStateException if the matcher's internal first variable is less than 0, but .find(), via the Matcher's boolean search(int from) method, will make sure that first is zero or greater unless no match is found, but if no match is found then .find() will return false, and we won't wind up in the loop body.

So what exactly is going on here?

Update: So I'f I encapsulate the above code so that it all runs in one unit test then it works. So I think the problem is related to having it in a class who's method is called from the unit test. But that's kind of weird. I'm going to dig into this aspect of the problem a bit more and then post an update.

Update: Ok, well I tried turning it off again and on again (I restarted my IntelliJ and recompiled my code) and now it's not broken anymore, so I think i must have screwed something up in that department.

Upvotes: 3

Views: 92

Answers (1)

David
David

Reputation: 14963

As per the last update on my question, restarting IntelliJ and recompiling my code fixed things.

Upvotes: 1

Related Questions