usr_27.txt ForVim version 9.2. Last change: 2026 Feb 14 VIM USER MANUALbyBramMoolenaar Search commands and patternsIn chapter 3a few simple search patterns were mentioned03.9. Vim candomuch more complex searches. This chapter explains the most often used ones.A detailed specification can be found here:patternOptions affecting how searchis done can be found here:search-options27.1 Ignoringcase27.2 Wrapping around the fileend27.3 Offsets27.4 Matching multiple times27.5 Alternatives27.6 Character ranges27.7 Character classes27.8 Matchinga line break27.9 Examples Next chapter:usr_28.txtFolding Previous chapter:usr_26.txt RepeatingTable of contents:usr_toc.txt==============================================================================27.1 IgnoringcaseBy default, Vim's searches arecase sensitive. Therefore, "include","INCLUDE", and "Include" are three different words anda search will matchonly one of them. Now switch on the'ignorecase' option::set ignorecaseSearch for "include" again, and nowit will match "Include", "INCLUDE" and"InClUDe". (Set the'hlsearch' option to quickly see whereapatternmatches.) You can switch this off again with::set noignorecaseBut let's keepit set, and search for "INCLUDE". It will match exactly thesame textas "include" did. Now set the'smartcase' option::set ignorecase smartcaseIf you haveapattern withat least oneuppercase character, the searchbecomescase sensitive. The ideais that you didn't have to type thatuppercase character, so youmust have doneit because you wantedcase tomatch. That's smart! With these twooptions set you find the following matches:patternmatcheswordword, Word, WORD, WoRd, etc.WordWordWORDWORDWoRdWoRdCASE IN ONE PATTERNIf you want to ignorecase for one specific pattern, you cando this byprepending the "\c" string. Using "\C" will make thepattern to match case.This overrules the'ignorecase' and'smartcase' options, when "\c" or "\C"isused their value doesn't matter.patternmatches\Cwordword\CWordWord\cwordword, Word, WORD, WoRd, etc.\cWordword, Word, WORD, WoRd, etc.A big advantage of using "\c" and "\C"is thatit sticks with the pattern.Thus if you repeatapattern from the search history, the same will happen, nomatter if'ignorecase' or'smartcase' was changed.Note:The use of "\" items in search patterns depends on the'magic' option.In this chapter we will assume'magic'is on, because thatis thestandard and recommended setting. If you would change'magic', manysearch patterns would suddenly become invalid.Note:If your search takes much longer than you expected, you can interruptit withCTRL-C onUnix andCTRL-Break on MS-Windows.==============================================================================27.2 Wrapping around the fileendBy default,a forward search starts searching for the givenstringat thecurrent cursor location. It then proceeds to theend of the file. Ifit hasnot found thestring by that time,it starts from the beginning and searchesfrom the start of the file to the cursor location. Keep in mind that whenrepeating the "n" command to search for the nextmatch, you eventually get back to the first match. If you don't notice thisyou keep searching forever! To give youa hint, Vim displays this message:search hit BOTTOM, continuing at TOPIf you use the "?" command, to search in the other direction, you get thismessage:search hit TOP, continuing at BOTTOMStill, you don't know when you are backat the first match. One way to seethisis by switching on the'ruler' option::set rulerVim will display the cursor position in the lower righthand corner of thewindow (in the status line if thereis one). It looks like this:101,29 84%The first numberis the line number of the cursor. Remember the line numberwhere you started, so that you can check if you passed this position again.NOT WRAPPINGTo turn off search wrapping, use the following command::set nowrapscanNow when the search hits theend of the file, an error message displays:E385: search hit BOTTOM without match for: foreverThus you can find all matches by going to the start of the file with "gg" andkeep searching until you see this message. If you search in the other direction, using "?", you get:E384: search hit TOP without match for: forever==============================================================================27.3 OffsetsBy default, the search command leaves the cursor positioned on the beginningof the pattern. You can tell Vim to leaveit some other place by specifyingan offset. For the forward search command "/", the offsetis specified byappendinga slash (/) and the offset:/default/2This command searches for thepattern "default" and then moves to thebeginning of the second line past the pattern. Using this command on theparagraph above, Vim finds theword "default" in the first line. Then thecursoris moved two lines down and lands on "an offset".If the offsetisa simple number, the cursor will be placedat the beginningof the line that many lines from the match. The offset number can be positiveor negative. Ifitis positive, the cursor moves down that many lines; ifnegative,it moves up.CHARACTER OFFSETSThe "e" offset indicates an offset from theend of the match. It moves thecursor onto the last character of the match. The command:/const/eputs the cursor on the "t" of "const". From that position, addinga number moves forward that many characters.This command moves to the character just after the match:/const/e+1A positive number moves the cursor to the right,a negative number movesit tothe left. For example:/const/e-1moves the cursor to the "s" of "const".If the offset begins with "b", the cursor moves to the beginning of thepattern. That's not very useful, since leaving out the "b" does the samething. It does get useful whena numberis added or subtracted. The cursorthen goes forward or backward that many characters. For example:/const/b+2Moves the cursor to the beginning of the match and then two characters to theright. Thusit lands on the "n".REPEATINGTo repeat searching for the previously used search pattern, but withadifferent offset, leave out the pattern:/that//eIs equal to:/that/eTo repeat with the same offset:/"n" does the same thing. To repeat while removinga previously used offset://SEARCHING BACKWARDSThe "?" command uses offsets in the same way, but youmust use "?" to separatethe offset from the pattern, instead of "/":?const?e-2The "b" and "e" keep their meaning, they don't change direction with the useof "?".START POSITIONWhenstartinga search,it normally startsat the cursor position. When youspecifya line offset, this can cause trouble. For example:/const/-2This finds the nextword "const" and then moves two lines up. If youuse "n" to search again, Vim could startat the current position and find thesame "const" match. Then using the offset again, you would be back where youstarted. You would be stuck! It could be worse: Suppose thereis another match with "const" in the nextline. Thenrepeating the forward search would find this match and move twolines up. Thus you would actually move the cursor back!When you specifya character offset, Vim will compensate for this. Thus thesearch startsa few characters forward or backward, so that the same matchisn't found again.==============================================================================27.4 Matching multiple timesThe "*" itemspecifies that the item beforeit can match any number of times.Thus:/a*matches "a", "aa", "aaa", etc. But also "" (the empty string), because zerotimesis included. The "*" only applies to the item directly before it. Thus "ab*" matches"a", "ab", "abb", "abbb", etc. To matcha wholestring multiple times,itmust be grouped into one item. Thisis done by putting "\(" beforeit and"\)" after it. Thus this command:/\(ab\)*Matches: "ab", "abab", "ababab", etc. And also "".To avoid matching the empty string, use "\+". This makes the previous itemmatch one or more times./ab\+Matches "ab", "abb", "abbb", etc. It does not match "a" when no "b" follows.To match an optional item, use "\=". Example:/folders\=Matches "folder" and "folders".SPECIFIC COUNTSTo matcha specific number of items use the form "\{n,m}". "n" and "m" arenumbers. The item beforeit will be matched "n" to "m" timesinclusive.Example:/ab\{3,5}matches "abbb", "abbbb" and "abbbbb". When "n"is omitted,it defaults to zero. When "m"is omittedit defaultsto infinity. When ",m"is omitted,it matches exactly "n" times.Examples:patternmatch count\{,4}0, 1, 2, 3 or 4\{3,}3, 4, 5, etc.\{0,1}0 or 1, sameas \=\{0,}0 or more, sameas *\{1,}1 or more, sameas \+\{3}3MATCHING AS LITTLE AS POSSIBLEThe items so far matchas many charactersas they can find. To matchas fewas possible, use "\{-n,m}". It works the sameas "\{n,m}", except that theminimal amount possibleis used. For example, use:/ab\{-1,3}Will match "ab" in "abbb". Actually,it will never match more than one b,because thereis no reason to match more. It requires something else to forceit to match more than the lower limit. The same rules apply to removing "n" and "m". It's even possible to removeboth of the numbers, resulting in "\{-}". This matches the item beforeitzero or more times,as fewas possible. The item by itself always matcheszero times. Itis useful when combined with something else. Example:/a.\{-}bThis matches "axb" in "axbxb". If thispattern would be used:/a.*bIt would try to matchas many charactersas possible with ".*", thusitmatches "axbxb"asa whole.==============================================================================27.5 AlternativesThe "or"operator inapatternis "\|". Example:/foo\|barThis matches "foo" or "bar". More alternatives can be concatenated:/one\|two\|threeMatches "one", "two" and "three". To match multiple times, the whole thingmust be placed in "\(" and "\)":/\(foo\|bar\)\+This matches "foo", "foobar", "foofoo", "barfoobar", etc. Another example:/end\(if\|while\|for\)This matches "endif", "endwhile" and "endfor".A related itemis "\&". This requires that both alternatives match in thesame place. The resulting match uses the last alternative. Example:/forever\&...This matches "for" in "forever". It will not match "fortuin", for example.==============================================================================27.6 Character rangesTo match "a", "b" or "c" you could use "/a\|b\|c". When you want to match allletters from "a" to "z" this gets very long. Thereisa shorter method:/[a-z]The[] construct matchesa single character. Inside you specify whichcharacters to match. You can includealist of characters, like this:/[0123456789abcdef]This will match any of the characters included. For consecutive charactersyou can specify the range. "0-3" stands for "0123". "w-z" stands for "wxyz".Thus the same commandas above can be shortened to:/[0-9a-f]To match the "-" character itself makeit the first or last one in the range.These special characters are accepted to makeit easier to use them insidea[] range (they can actually be used anywhere in the search pattern):\e<Esc>\t<Tab>\r<CR>\b<BS>There area few more special cases for[] ranges, see/[] for the wholestory.COMPLEMENTED RANGETo avoid matchinga specific character, use "^"at the start of the range.The[] item then matches everything but the characters included. Example:/"[^"]*" "a doublequote [^"] any character thatis nota doublequote *as manyas possible "a doublequote againThis matches "foo" and "3!x", including the double quotes.PREDEFINED RANGESA number of ranges are used very often. Vim providesa shortcut for these.For example:/\aFinds alphabetic characters. Thisis equal to using "/[a-zA-Z]". Here areafew more of these:itemmatchesequivalent\ddigit[0-9]\Dnon-digit[^0-9]\xhex digit[0-9a-fA-F]\Xnon-hex digit[^0-9a-fA-F]\swhitespace[] (<Tab> and<Space>)\Snon-white characters[^] (not<Tab> and<Space>)\llowercase alpha[a-z]\Lnon-lowercase alpha[^a-z]\uuppercase alpha[A-Z]\Unon-uppercase alpha[^A-Z]Note:Using these predefined ranges worksa lot faster than the characterrangeit stands for.These items can not be used inside []. Thus "[\d\l]" does NOT work tomatcha digit orlowercase alpha. Use "\(\d\|\l\)" instead.See/\s for the wholelist of these ranges.==============================================================================27.7 Character classesThe character range matchesa fixed set of characters.A characterclassissimilar, but with an essential difference: The set of characters can beredefined withoutchanging the search pattern. For example, search for this pattern:/\f\+The "\f" item stands for file name characters. Thus this matchesa sequenceof characters that can bea file name. Which characters can be part ofa file name depends on the system you areusing. On MS-Windows, thebackslashis included, onUnixitis not. Thisisspecified with the'isfname' option. The default value forUnix is::set isfnameisfname=@,48-57,/,.,-,_,+,,,#,$,%,~,=For other systems the default valueis different. Thus you can makea searchpattern with "\f" to matcha file name, andit will automatically adjust tothe system you are usingit on.Note:Actually,Unix allows using just about any character ina file name,including white space. Including these characters in'isfname' wouldbe theoretically correct. Butit would makeit impossible to find theend ofa file name in text. Thus the default value of'isfname'isacompromise.The character classes are:itemmatchesoption\iidentifier characters'isident'\Ilike \i, excluding digits\kkeyword characters'iskeyword'\Klike \k, excluding digits\pprintable characters'isprint'\Plike \p, excluding digits\ffile name characters'isfname'\Flike \f, excluding digits==============================================================================27.8 Matchinga line breakVim can findapattern that includesa line break. You need to specify wherethe line break happens, because all items mentioned so far don't matcha linebreak. To check fora line break ina specific place, use the "\n" item:/one\ntwoThis will matchata line that ends in "one" and the next line starts with"two". To match "one two"as well, you need to matchaspace ora linebreak. The item to use foritis "\_s":/one\_stwoTo allow any amount of white space:/one\_s\+twoThis also matches when "one "isat theend ofa line and " two"at thestart of the next one."\s" matches white space, "\_s" matches whitespace ora line break.Similarly, "\a" matches an alphabetic character, and "\_a" matches analphabetic character ora line break. The other character classes and rangescan be modified in the same way byinsertinga "_".Many other items can be made to matcha line break by prepending "\_". Forexample: "\_." matches any character ora line break.Note:"\_.*" matches everything until theend of the file. Be careful withthis,it can makea search command very slow.Another exampleis "\_[]",a character range that includesa line break:/"\_[^"]*"This findsa text in doublequotes that may be split up in several lines.==============================================================================27.9 ExamplesHere area few search patterns you might find useful. This shows how theitems mentioned above can be combined.FINDING A CALIFORNIA LICENSE PLATEA samplelicense plate numberis "1MGU103". It has one digit, threeuppercaseletters and three digits. Directly putting this intoa search pattern:/\d\u\u\u\d\d\dAnother wayis to specify that there are three digits and letters withacount:/\d\u\{3}\d\{3}Using[] ranges instead:/[0-9][A-Z]\{3}[0-9]\{3}Which one of these you should use? Whichever one you can remember. Thesimple way you can rememberis much faster than the fancy way that you can't.If you can remember them all, then avoid the last one, because it's both moretyping and slower to execute.FINDING AN IDENTIFIERInC programs (and many other computer languages) an identifier starts withaletter and further consists of letters and digits. Underscores can be usedtoo. This can be found with:/\<\h\w*\>"\<" and "\>" are used to find only whole words. "\h" stands for "[A-Za-z_]"and "\w" for "[0-9A-Za-z_]".Note:"\<" and "\>" depend on the'iskeyword' option. Ifit includes "-",for example, then "ident-"is not matched. In this situation use:/\w\@<!\h\w*\w\@!This checks if "\w" does not match before or after the identifier.See/\@<! and/\@!.==============================================================================Next chapter:usr_28.txtFoldingCopyright: seemanual-copyright vim:tw=78:ts=8:noet:ft=help:norl: