我知道它已经在另一个答案中详细解释了(包括对一般使用的正则表达式的更好解释),但是我最近遇到了这个正则表达式而没有解释,所以我自己添加了一些评论。我想我也会在这里分享它,让其他人看到。
首先要注意的是,正则表达式使用一元数作为整数。因此,在Java代码中,将整数转换为包含许多()字符的字符串。此字符串包含哪个字符并不重要,重要的是长度对于一元数。(例如,Java 11+ 中的替代方案可能是 ,并且它仍然可以按预期工作。String s = new String(new char[n]);
n
'\0'
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