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 ofseqthat fits at that position- If none of
seqmatches, 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
seqas possible - Unlike
\(a\|ab\|abc\),\%[abc]is cleaner and faster to write for prefix-optional sequences - Works in both
/search and:ssubstitution patterns - To make multiple independent characters optional, nest:
/\%[abc]\%[def]