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!
matches()orfind()before you can callstart(). Javadoc even documents this: ThrowsIllegalStateExceptionif no match has yet been attempted, or if the previous match operation failed. Javadoc ofMatchersays: Once created, a matcher can be used to perform three different kinds of match operations: Thematchesmethod [...] ThelookingAtmethod [...] Thefindmethod [...].*true, indicating a successful match? You can't ask for match result values until you have successfully performed a match. Makes sense, right?!? --- It's like asking for an apple, being told that there aren't any, then asking how big they are. It is an unanswerable question, which is why you get an exception.