Vim Tips Wiki

Matching optional parts of a word

1,624pages on
this wiki
Add New Page
Talk0 Share
Tip 254 Printable Monobook Previous Next

created 2002 · complexity basic · author RobertKellyIV · version 6.0

This code fragment is suitable to drop into DrChip's CStubs from script#1269.

If you have ever wanted to match parts of a word you may have considered something like:

if wrd == "re" || wrd == "ret" || wrd == "retu" || wrd == "retur"
  "do something

Although the above works well enough it is a pain to maintain and add new words (not to mention it's just a touch messy).

A more elegant (and easier to use I believe) method would be to use \%[] as part of a pattern.

For instance, "\\<re\\%[tur]\\>" will match "re", "ret", "retu" or "retur"


\\< = start of word
re = first letters of word we want to require to match
\\%[tur] = optionally match chars between the braces, i.e. 't', 'tu' or 'tur'
\\> = end of word

So, we can use this as a pattern for match like so (in DrChip's CStubs):

elseif match(wrd, "\\<re\\%[tur]\\>") > -1
  exe "norm! bdWireturn\<Esc>"

Which, I think, is a little better than the longer alternative:

" vs
elseif wrd == "re" || wrd == "ret" || wrd == "retu" || wrd == "retur"
  exe "norm! bdWireturn\<Esc>"


Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

Also on Fandom

Random Wiki