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

How do I search for text that appears after or before a specific pattern without including the pattern in the match?

Answer

/\v(pattern)@<=match

Explanation

Vim supports zero-width assertions (lookahead and lookbehind) in its regex engine. These let you match text that is preceded or followed by a specific pattern without including that pattern in the match itself. This is invaluable for precise search-and-replace operations where context matters.

How it works

Using \v (very magic mode) for cleaner syntax:

  • (pattern)@<= — positive lookbehind: match only if pattern precedes the match
  • (pattern)@<! — negative lookbehind: match only if pattern does NOT precede the match
  • (pattern)@= — positive lookahead: match only if pattern follows the match
  • (pattern)@! — negative lookahead: match only if pattern does NOT follow the match

The key detail is that @ modifiers apply to the preceding atom (the group in parentheses), and they assert a condition without consuming characters.

Example

To find all numbers that follow a dollar sign, without including the $ in the match:

/\v(\$)@<=\d+

In the text Price: $42 and EUR 99, this matches 42 but not 99.

To replace values after color: in CSS without touching the property name:

:%s/\v(color: )@<=\w+/blue/g

Changes color: red to color: blue while leaving the color: prefix intact.

Tips

  • Without \v, use \(pattern\)\@<= — the very magic flag saves a lot of backslashes
  • Combine lookahead and lookbehind: /\v(\$)@<=\d+(\.)@! matches dollar amounts without a decimal point
  • Lookbehind in Vim can be variable-width, unlike many other regex engines

Next

How do I ignore whitespace changes when using Vim's diff mode?