我知道它已经在另一个答案中进行了很多详细的解释(包括对一般使用的正则表达式的更好解释),但是我最近遇到了这个正则表达式而没有解释,所以我自己为此添加了一些评论。我想我也会在这里分享给其他人看。
首先要注意的是正则表达式对整数使用一元。因此String s = new String(new char[n]);
,在 Java 代码中,会将整数n
转换为包含许多 ( '\0'
) 个字符的字符串。这个字符串包含哪个字符并不重要,重要的是一元的长度。(例如,Java 11+ 中的替代方案可能是String s = "x".repeat(n);
,它仍然可以按预期工作。)
至于正则表达式本身:
"(?x) .? | ( \\2?+ (\\1|^.) )* .." # Since this is a Java-String, where the `\` are escaped
# as `\\` and `String#matches` also implicitly adds a
# leading/trailing `^...$` to regex-match the entire
^(?x) .? | ( \2?+ (\1 |^.) )* ..$ # String, the actual regex will be this:
# The `(?x)` is used to enable comments and whitespaces,
# so let's ignore those for now:
^.?|(\2?+(\1|^.))*..$
( )* # 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
# 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 his optional is that this group isn't defined
# yet in the second iteration. The reason we have the `+`
# 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,8,... will add up to 3,6,11,19,...
.. # They are all two less than the Fibonacci numbers, so
# we add 2 at the end.
# Now it's only missing the 0 and 1 of the Fibonacci
.?| # numbers, so we'll account for those separately