Vim logo vim online Vim Book Ad

basic Tip #254: Using \%[] to easily match parts of a word.

 tip karma   Rating 8/7, Viewed by 704 

created:   May 30, 2002 7:22      complexity:   basic
author:   RobertKellyIV      as of Vim:   6.0

This code fragment is suitable to drop into DrChip's CStubs.
After much searching I was unable to find a tip nor script number to referance, I believe where I found Dr. Chip's CStubs originally : http://users.erols.com/astronaut/vim/vimscript/drcstubs.vim
Thank you Dr. Chip! (=


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

Althought the above works well enough it is a pain to maintain and add new words (not to mention its 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"

*breakdown*
\\< = start of word
re = first letters of word we want to require to match
\\%[tur] = optionally match chars bewteen 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>"


Just another one of those VIM things that made me smile :)

 rate this tip  Life Changing Helpful Unfulfilling 

<<The power of | (v75|r- actually...) | arbitrary tags for file names >>

Additional Notes

If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
SourceForge Logo