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

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

Answer

/foo\|bar

Explanation

How it works

The \| operator in Vim's search pattern works like a logical OR, letting you match any one of several alternatives. The search /foo\|bar matches lines containing either foo or bar (or both).

You can chain multiple alternatives together:

  • /error\|warning\|fatal matches any of the three words
  • /\.js\|\.ts\|\.jsx matches common JavaScript file extensions

To group alternatives and combine them with other pattern elements, use \( and \) for grouping:

  • /\(get\|set\)Value matches getValue or setValue
  • /log_\(error\|warn\|info\) matches log_error, log_warn, or log_info

If you prefer cleaner syntax, use very magic mode with \v:

  • /\v(get|set)Value is equivalent to /\(get\|set\)Value

Example

Suppose you are reviewing code for potential issues and want to find all TODO and FIXME comments:

/TODO\|FIXME

Vim highlights and jumps between all occurrences of both words. Press n to cycle through all matches of either pattern.

For a more targeted search in a log file:

/\vERROR|CRITICAL|FATAL

Using \v (very magic mode) avoids the need to escape the pipe characters.

This also works in substitute commands:

:%s/\(true\|false\)/BOOLEAN/g

This replaces every occurrence of true or false with BOOLEAN.

Next

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