aslconwnb
aslconwnb

Reputation: 61

Java Regular Expressions Not Compiling - No Match Available Error

I have been working on this project which requires converting a file to a string and then finding the locations of certain strings within the string. I am trying to use the Pattern and Matcher classes to do this. Please take a look at my code below (java):

String begin = "TOSS-UP" + "\\s*" + j;
String end = "TOSS-UP" + "\\s*" + (j+1);
Pattern beginPattern = Pattern.compile(begin);
Pattern endPattern = Pattern.compile(end);
System.out.println(beginPattern);
Matcher beginMatcher = beginPattern.matcher(input);
Matcher endMatcher = endPattern.matcher(input);
int beginPosition = beginMatcher.start();
int endPosition = endMatcher.start();

where j is a variable in a for loop (that starts out at 1 and works its way up to 24) and input is a string that starts out as such:

ROUND 1 TOSS-UP 1) ... TOSS-UP 2) ... TOSS-UP 3) ... TOSS-UP 4) ...

I need to use regex since every so often this string will have a \n between the TOSS-UP and the number (instead of a simple space).

I'm new to regex, trying to learn what I can off internet examples, and I can't see why this program can't compile. The error eclipse gives me is:

Exception in thread "main" java.lang.IllegalStateException: No match available 
at java.util.regex.Matcher.start 
at Driver.main

Any help fixing the regex would be appreciated. If anyone else has another solution to the problem, please let me know. Thanks!

Upvotes: 2

Views: 926

Answers (1)

cs95
cs95

Reputation: 403248

Call the matches() function first, before trying to get anything from the matcher object. Calling matches() will trigger the match, and a boolean value returned depending on whether there was a match or not.

... // as usual
int beginPosition = -1;
int endPosition = -1;
if(beginMatcher.matches()) {
     beginPosition = beginMatcher.start();
} 

if(endMatcher.matches()) {
    endPosition = endMatcher.start();
}

As pointed out by @MikeSamuel in the comments, if you want only the first match, perhaps .find() would be better. Also, consider adding a \b to the end of your regex so TOSS-UP 1 is not found in TOSS-UP 10, for example.

Upvotes: 2

Related Questions