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

How do I search for multiple alternative patterns at once in Vim?

Answer

/foo\|bar\|baz

Explanation

Vim's search supports alternation with the \| operator, allowing you to find any one of several patterns in a single search. This is far more efficient than searching for each pattern separately and is essential for complex code searches.

How it works

  • \| — the alternation (OR) operator in Vim regex
  • Matches the longest alternative that matches at each position
  • Alternatives are tried left to right
  • Can be combined with grouping: \(foo\|bar\)baz

Example

/foo\|bar\|baz
Text: I like foo and bar but not baz
All three words are highlighted as matches

Using with very magic mode:

/\v(error|warn|fatal)

Tips

  • Use with :g to act on lines matching any alternative: :g/error\|warn/p
  • Group alternatives when combining with other atoms: \(get\|set\)Value
  • In very magic mode (\v), use | without escaping: /\v(foo|bar|baz)
  • Alternation has the lowest precedence — ab\|cd means (ab)|(cd), not a(b|c)d

Next

How do I return to normal mode from absolutely any mode in Vim?