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

How do I match an optional sequence of characters at the end of a word in a Vim regex?

Answer

\%[abc]

Explanation

The \%[...] atom matches each character in the brackets optionally and greedily, one by one from left to right. It is Vim's shorthand for matching optional character suffixes — useful when a word may appear in abbreviated or full form.

How it works

\%[abc] attempts to match a, and if successful tries b, and if successful tries c. It matches the longest possible prefix of abc starting from the beginning. Unlike (abc)? which matches all-or-nothing, \%[...] accepts partial matches:

  • \%[our] matches "", "o", "ou", or "our"

This mirrors how Vim itself allows Ex commands to be abbreviated: :s, :su, :sub and :substitute all work because :substitute can be shortened to any unique prefix.

Example

Search for both color and colour in a file:

/colou\%[r]

This matches "colou" followed by an optional "r", finding both American and British spellings.

Find both :w and :write in a mappings file:

/\<w\%[rite]\>

This matches w, wr, wri, writ, or write as whole words.

Tips

  • Cannot be nested: \%[a\%[b]c] is invalid
  • Combine with \< and \> word boundaries to avoid partial-word matches
  • Useful in substitute commands to normalize abbreviations: :%s/colou\%[r]/color/g
  • For a plain optional character, \%[r] is equivalent to r\? but reads more clearly in context

Next

What built-in LSP keymaps does Neovim 0.10+ provide automatically when a language server is attached?