Using Raku (formerly known as Perl_6)
~$ raku -pe 's:g/ foo <?before \s* bar> //;' file
#OR
~$ raku -pe 's:g/ <(foo)> \s* bar //;' file
The answers above are coded in Raku, a member of the Perl-family of programming languages. Advantages of Raku include high-level Unicode support built-in, as well as a robust/refined Regex implementation. Above, Raku Regexes are whitespace-tolerant in the recognition domain (left half of s///
), so Regex atoms can be spread-out (and lined up). Also, all Regex modifiers such as :global
(or :g
) move to the head of the s///
operator in Raku. Like Perl, the global flag or "adverb" allows more than one match per line.
The first answer is a rough translation of @jcaron's excellent Perl(5) answer. Note in Raku, positive lookaheads are spelled <?before ... >
. The second answer uses Raku's <(
...)>
capture markers, so that after all three atoms match, only foo
is retained in the capture (and deleted in the replacement).
Both answers specifically change foo
before bar
with only whitespace in-between. This is an important point: given the phrase "my valentine, my bloody valentine" the Raku code s:g/my <?before \s* valentine> //
will remove the first "my" (because "my-is_before-valentine"), but the second "my" remains untouched.
https://docs.raku.org/language/regexes
https://raku.org