vimtricks.wiki Concise Vim tricks, one at a time.

How do I match a pattern only if it is NOT followed by something?

Answer

/pattern\@!

Explanation

The \@! atom is a negative lookahead in Vim regex. It matches a position where the preceding pattern does NOT match going forward.

How it works

  • pattern\@! succeeds if pattern does not match at this position
  • It does not consume characters — it only asserts
  • Must be used carefully with surrounding context

Example

Match foo not followed by bar:

/foo\(bar\)\@!

In the text foobar foobaz foo, this matches foo in foobaz and standalone foo, but not in foobar.

Tips

  • \@= is positive lookahead (matches if followed by)
  • \@<! is negative lookbehind
  • \@<= is positive lookbehind
  • In very magic mode: /\vfoo(bar)@!
  • These are zero-width — they do not consume input

Next

How do you yank a single word into a named register?