0

I am writing a compiler for a Java-like language and need to match occurrences of one-line comments of the style // Comment. for my tokenizer.

My attempt:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchOneLineComment {
  public static void main(String[] args) {
    Matcher matcher = Pattern.compile("//(.*)").matcher("//abc");
    System.out.println(matcher.group()); // should print "//abc"... right?
  }
}

However I get the following error:

Exception in thread "main" java.lang.IllegalStateException: No match found
    at java.util.regex.Matcher.group(Matcher.java:485)
    at java.util.regex.Matcher.group(Matcher.java:445)
    at MatchOneLineComment.main(MatchOneLineComment.java:7)

Any help would be greatly appreciated.

1 Answer 1

2

Don't forget to call Matcher#find()

matcher.find();

and check the result before you call group().

From the javadoc

Attempts to find the next subsequence of the input sequence that matches the pattern.

This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

If the match succeeds then more information can be obtained via the start, end, and group methods.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this was my problem. Will accept in a minute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.