How do I search for multiple spellings or word endings with a single Vim pattern?
Answer
/colour\%[s]
Explanation
Vim's \%[...] optional atom lets you specify a sequence of characters that are matched as a whole, or not at all. Any prefix of the bracketed string is also valid—making it perfect for handling spelling variants, optional suffixes, and abbreviated words without resorting to \| alternation.
How it works
\%[...]matches the enclosed character sequence optionally, accepting any prefix of the content/colour\%[s]matchescolourandcolours/organiz\%[ation]matchesorganiz,organiza,organizat,organizati,organizatio, andorganization- The match is greedy: Vim matches as many characters in
\%[...]as possible - Unlike
\(foo\)\?, this works on a sequence of characters, not just a single atom
Example
/col\%[our]\%[s]
This single pattern matches all of: col, colo, colou, colour, colours—useful when searching a codebase that uses both British and abbreviated spellings.
/func\%[tion]
Matches func and function simultaneously—handy in mixed JavaScript/CoffeeScript files.
Tips
- Combine with
\cfor case-insensitive matching:/\ccol\%[our] - Use in
:ssubstitutions to normalize spellings::%s/col\%[our]s\?/color/g - Note that
\%[...]does not work as an alternation operator—each character inside is optional in sequence from left to right, not a set of alternatives - See
:help /\%[]for the full specification