In Regexes§
See primary documentation in context for Lookbehind assertions
To check that a pattern appears after another pattern, use a lookbehind assertion via the after
assertion. This has the form:
<?after pattern>
Therefore, to search for the string bar
immediately preceded by the string foo
, use the following regexp:
/ bar /
For example:
say "foobar" ~~ / bar /; # OUTPUT: «bar»
However, if you want to search for a pattern which is not immediately preceded by some pattern, then you need to use a negative lookbehind assertion, this has the form:
<!after pattern>
Hence all occurrences of bar
which do not have foo
before them would be matched by
say "fotbar" ~~ / bar /; # OUTPUT: «bar»
These are, as in the case of lookahead, zero-width assertions which do not consume characters, like here:
say "atfoobar" ~~ / (.**3) .**2 bar /;# OUTPUT: «「atfoobar」 0 => 「atf」»
where we capture the first 3 of the 5 characters before bar, but only if bar
is preceded by foo
. The fact that the assertion is zero-width allows us to use part of the characters in the assertion for capture.