Wikia

Vim Tips Wiki

Matching optional parts of a word

Talk0
1,613pages on
this wiki
Revision as of 05:28, September 29, 2008 by JohnBot (Talk | contribs)

Tip 254 Printable Monobook Previous Next

created May 30, 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"

Explanation:

\\< = 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>"

Comments

Around Wikia's network

Random Wiki