N equivalent for vim’s \zs in sed or perl

perlregular expressionsedvim

In vim we can use the \zs atom to say "really begin the match right here":

:%s/funnyword\zs.*$/otherword/

Is there an equivalent for sed or even perl?

Best Answer

In Perl (and PCRE) this is achievable with a zero-width lookbehind:

(?<=funnyword).*$

which matches "funnyword", but doesn't consume it as part of the match. These only work with fixed-length text in the lookbehind. You can also use negative lookbehinds ((?<!...)) to specify that some text isn't there.

In any reasonably recent version of Perl, \K is almost an exact substitute for \zs as you're using it:

funnyword\K.*$

\K discards everything matched so far but continues matching from that point onwards. The part before \K doesn't have to be fixed-length. This is also in PCRE now, but I'm not sure what version it came in.

\ze can be achieved with a zero-width lookahead instead, using (?=...). That pattern doesn't need to be fixed-length.


Because sed uses POSIX BREs, there is no lookaround. In this case, though, you can fairly easily simulate it using an ordinary capturing group:

sed -e 's/\(funnyword\).*$/\1otherword/'

You can do the same for positive lookahead. If you really have a more complicated requirement you may have to look to Perl or some other approach.

Related Question