有效的解决办法(
demo
). 这个问题的解决方案是99个步骤,在这个简单的例子中,这是不必要的牺牲。在有些情况下,牺牲,如果有的话,是非常谨慎的。
结果很简单。生成捕获组1
占有
. 这意味着无论它捕捉到什么,如果regex试图回溯,它都不会投降。这意味着一旦它决定在数字前面加上
$
,如果数字后面还跟着一个
$
. 它会放弃并继续前进,寻找下一个边界,然后是数字,并观察周围环境。
( # capture 1, because we can't quantify lookarounds
(?<=\$) # Asserts that $ precedes current position
)?+ # close capture 1, make it "optional" (0 or 1 times)
# the possessive quantifier is the only change to the regex
# + is only 'possessive' when it's the second character of a quantifier
\b # boundary
\d+ # digits
\b # boundary
(?(1) # conditional that capture #1 was a success
(?!\$) # if successful, assert that it is not followed by a #
|
(?=\$) # unsuccessful, assert that this position is followed by a $
)