I've written a regex pattern to find Fibonacci numbers (it doesn't matter why, I just did). It works wonderfully as expected (see on ideone.com):
String FIBONACCI =
"(?x) .{0,2} | (?: (?=(\\2?)) (?=(\\2\\3|^.)) (?=(\\1)) \\2)++ . ";
for (int n = 0; n < 1000; n++) {
String s = new String(new char[n]);
if (s.matches(FIBONACCI)) {
System.out.print(n + " ");
}
} // 0 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
A possessive repetition (i.e. ++ on the main "loop") is crucial, because you don't want backtracking with this matching algorithm. However, making the repetition backtrackable (i.e. just + on the main "loop") results not in mismatches, but rather a runtime exception!!! (as seen on ideone.com):
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1
at java.lang.String.charAt(String.java:686)
at java.lang.Character.codePointAt(Character.java:2335)
at java.util.regex.Pattern$CharProperty.match(Pattern.java:3344)
at java.util.regex.Pattern$GroupCurly.match0(Pattern.java:3994)
at java.util.regex.Pattern$GroupCurly.match0(Pattern.java:3966)
at java.util.regex.Pattern$GroupCurly.match(Pattern.java:3916)
at java.util.regex.Pattern$Branch.match(Pattern.java:4114)
at java.util.regex.Matcher.match(Matcher.java:1127)
at java.util.regex.Matcher.matches(Matcher.java:502)
at java.util.regex.Pattern.matches(Pattern.java:930)
at java.lang.String.matches(String.java:2090)
Can someone explain what happened here? Is this a bug in the Java regex engine?