Skip to content

Behaviour of calling matches() and then find() doesn't match java.util.regex #200

Description

@cushon

In the following example, the behaviour of re2j doesn't match the behaviour of java.util.regex.

With java.util.regex, calling matches() and then find() advances to a second match (which doesn't exist), so it throws an IllegalStateException.

public class T {
  public static void main(String[] args) {
    String pattern = "([1-5][0-9]{2})-([1-5][0-9]{2})";
    String input = "201-299";
    {
      System.err.println("> re2j");
      try {
        var p = com.google.re2j.Pattern.compile(pattern);
        var m = p.matcher(input);
        if (m.matches()) {
          m.find();
          System.err.println(
              "match: " + Integer.parseInt(m.group(1)) + " - " + Integer.parseInt(m.group(2)));
        }
      } catch (Exception e) {
        System.err.println(e.getClass() + " " + e.getMessage());
      }
    }
    {
      System.err.println("> java.util.regex");
      try {
        var p = java.util.regex.Pattern.compile(pattern);
        var m = p.matcher(input);
        if (m.matches()) {
          m.find(); // java.util.regex reports a match if the extra call to find() is removed
          System.err.println(Integer.parseInt(m.group(1)) + " - " + Integer.parseInt(m.group(2)));
        }
      } catch (Exception e) {
        System.err.println(e.getClass() + " " + e.getMessage());
      }
    }
  }
}
> re2j
match: 201 - 299
> java.util.regex
class java.lang.IllegalStateException No match found

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions