google / google/re2j

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

Open
#200 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
1.3k
Forks
165
PR merge metrics
No merged PRs in 30d

Description

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`.

```java
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
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.