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

How do I search for a second pattern relative to where the first one matched?

Answer

/pattern1/;/pattern2/

Explanation

Vim's search offsets allow chaining two patterns together with a semicolon. /pattern1/;/pattern2/ first jumps to pattern1, then — from that position — immediately searches forward for pattern2. This lets you navigate to something that only makes sense relative to another match, without writing a single complex regex.

How it works

  • /pattern1/ — normal forward search; jumps to the first match
  • ; — after jumping to pattern1, search forward from there
  • /pattern2/ — the second search, executed from the position of pattern1's match
  • The cursor lands on pattern2
  • You can chain more than two: /a/;/b/;/c/ finds c after b after a
  • Works with ? for backward searches too

Example

In a large config file, jump to the [database] section header and then find the first host = line within it:

/\[database\]/;/host =/

This is more precise than /host =/ alone, which might land on a host = in the wrong section.

Tips

  • Use n and N after a chained search to repeat the compound jump
  • The semicolon offset is especially powerful with %s ranges — combine it with :g for complex multi-pattern edits
  • In very magic mode (\v), the syntax is the same: /\v\[database\]/;/host =/
  • The first pattern can have its own offset too: /pattern1/e;/pattern2/ lands after the end of pattern1 before searching for pattern2

Next

How do I run a search and replace only within a visually selected region?