Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top