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\|fatalmatches any of the three words/\.js\|\.ts\|\.jsxmatches common JavaScript file extensions
To group alternatives and combine them with other pattern elements, use \( and \) for grouping:
/\(get\|set\)ValuematchesgetValueorsetValue/log_\(error\|warn\|info\)matcheslog_error,log_warn, orlog_info
If you prefer cleaner syntax, use very magic mode with \v:
/\v(get|set)Valueis 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.