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

How do I make part of a search pattern optional so it matches with or without that sequence?

Answer

\%[seq]

Explanation

Vim's \%[seq] atom makes the sequence seq optional in a pattern — matching any prefix of the sequence (including nothing). This is more powerful than \? (which makes only a single character optional) because it handles multi-character optional suffixes elegantly.

How it works

  • \%[seq] matches the longest prefix of seq that fits at that position
  • If none of seq matches, it still succeeds (matches the empty string)
  • Useful for matching spelling variants or abbreviated forms of words

Example

Match both British and American spellings in one pattern:

/colo\%[u]r

This matches color (skips u) and colour (includes u).

Match command abbreviation prefixes like Vim's own :s[ubstitute]:

/s\%[ubstitute]

Matches s, su, sub, ..., substitute.

Practical search and replace for both spellings:

:%s/colo\%[u]r/color/g

Replaces both color and colour with color.

Tips

  • The matching is greedy — it consumes as much of seq as possible
  • Unlike \(a\|ab\|abc\), \%[abc] is cleaner and faster to write for prefix-optional sequences
  • Works in both / search and :s substitution patterns
  • To make multiple independent characters optional, nest: /\%[abc]\%[def]

Next

What is the difference between the inner word (iw) and inner WORD (iW) text objects in Vim?