- .?|(\\2?+(\\1|^.))*.. // Full regex:
- ( )* // First capture group repeated 0 or more times.
- // On each iteration it matches one Fibonacci number
- |^. // In the first iteration, we simply match 1 as base case.
- // Afterwards, the ^ can no longer match, so the second alternative is used
- \\2?+ // If possible, match group 2. This ends up being the Fibonacci number before the last.
- // The reason we need to make this optional is that this group isn't defined yet
- // on the second iteration. The reason we wrap it in an atomic group is to prevent backtracking:
- // if group 2 exists, we *have* to include it in the match, otherwise we would allow
- // smaller increments.
- (\\1| ) // Finally, match the previous Fibonacci number and store it in group 2 so that it becomes
- // the second-to-last Fibonacci number in the next iteration
- .. // This in total ends up adding Fibonacci numbers starting at 1 (i.e. 1,2,3,5,... will add up to
- // 3,6,11,19,... They are two less than the Fibonacci numbers, so we add a 2 at the end.
- .?| // Now it's only missing the 0 and 1 of the Fibonacci numbers, so we account for those separately
RAW Paste Data