Pattern
Nvim:help pages,generated fromsource using thetree-sitter-vimdoc parser.
Patterns and search commands
The very basics can be found in section
03.9 of the user manual. A few moreexplanations are in chapter 27
usr_27.txt.
//{pattern}[/]<CR>Search forward for the [count]'th occurrence of
{pattern}exclusive.
/{pattern}/{offset}<CR>Search forward for the [count]'th occurrence of
{pattern} and go
{offset} lines up or down.
linewise.
//{offset}<CR>Search forward for the [count]'th occurrence of thelatest used pattern
last-pattern with new
{offset}. If
{offset} is empty no offset is used.
??{pattern}[?]<CR>Search backward for the [count]'th previousoccurrence of
{pattern}exclusive.
?{pattern}?{offset}<CR>Search backward for the [count]'th previousoccurrence of
{pattern} and go
{offset} lines up ordown
linewise.
??{offset}<CR>Search backward for the [count]'th occurrence of thelatest used pattern
last-pattern with new
{offset}. If
{offset} is empty no offset is used.
nnRepeat the latest "/" or "?" [count] times.If the cursor doesn't move the search is repeated withcount + 1.
last-pattern NNRepeat the latest "/" or "?" [count] times inopposite direction.
last-pattern starE348E349*Search forward for the [count]'th occurrence of theword nearest to the cursor. The word used for thesearch is the first of:1. the keyword under the cursor
'iskeyword'2. the first keyword after the cursor, in the current line3. the non-blank word under the cursor4. the first non-blank word after the cursor, in the current lineOnly whole keywords are searched for, like with thecommand "/\<keyword\>".
exclusive'ignorecase' is used,
'smartcase' is not.
v_star-default{Visual}*In Visual mode, search forward for the current selection.
default-mappings ##Same as "*", but search backward. The pound sign(character 163) also works. If the "#" key works asbackspace, try using "stty erase
<BS>" before startingVim (
<BS> is
CTRL-H or a real backspace).
v_#-default{Visual}#In Visual mode, search backward for the current selection.
default-mappings gstarg*Like "*", but don't put "\<" and "\>" around the word.This makes the search also find matches that are not awhole word.
g#g#Like "#", but don't put "\<" and "\>" around the word.This makes the search also find matches that are not awhole word.
gdgdGoto local Declaration. When the cursor is on a localvariable, this command will jump to its declaration.This was made to work for C code, in other languagesit may not work well.First Vim searches for the start of the currentfunction, just like "[[". If it is not found thesearch stops in line 1. If it is found, Vim goes backuntil a blank line is found. From this position Vimsearches for the keyword under the cursor, like with"*", but lines that look like a comment are ignored(see
'comments' option).Note that this is not guaranteed to work, Vim does notreally check the syntax, it only searches for a matchwith the keyword. If included files also need to besearched use the commands listed in
include-search.After this command
n searches forward for the nextmatch (not backward).
gDgDGoto global Declaration. When the cursor is on aglobal variable that is defined in the file, thiscommand will jump to its declaration. This works justlike "gd", except that the search for the keywordalways starts in line 1.
1gd1gdLike "gd", but ignore matches inside a {} block thatends before the cursor position.
1gD1gDLike "gD", but ignore matches inside a {} block thatends before the cursor position.
CTRL-CCTRL-CInterrupt current (search) command.In Normal mode, any pending command is aborted.
:noh:nohlsearch:noh[lsearch]Stop the highlighting for the
'hlsearch' option. Itis automatically turned back on when using a searchcommand, or setting the
'hlsearch' option.This command doesn't work in an autocommand, becausethe highlighting state is saved and restored whenexecuting autocommands
autocmd-searchpat.Same thing for when invoking a user function.
While typing the search pattern the current match will be shown if the
'incsearch' option is on. Remember that you still have to finish the searchcommand with
<CR> to actually position the cursor at the displayed match. Oruse
<Esc> to abandon the search.
When
'shortmess' does not include the "S" flag, Vim will automatically show anindex, on which the cursor is. This can look like this:
[1/5]Cursor is on first of 5 matches.[1/>99]Cursor is on first of more than 99 matches.[>99/>99]Cursor is after 99 match of more than 99 matches.[?/??]Unknown how many matches exists, generating the statistics was aborted because of search timeout.
Note: the count does not take offset into account.
When no match is found you get the error:
E486 Pattern not foundNote that for the
:global command, you get a normal message "Pattern notfound", for Vi compatibility.For the
:s command the "e" flag can be used to avoid the error message
:s_flags.
search-offset{offset}These commands search for the specified pattern. With "/" and "?" anadditional offset may be given. There are two types of offsets: line offsetsand character offsets.
The offset gives the cursor position relative to the found match: [num][num] lines downwards, in column 1 +[num][num] lines downwards, in column 1 -[num][num] lines upwards, in column 1 e[+num][num] characters to the right of the end of the match e[-num][num] characters to the left of the end of the match s[+num][num] characters to the right of the start of the match s[-num][num] characters to the left of the start of the match b[+num][num] identical to s[+num] above (mnemonic: begin) b[-num][num] identical to s[-num] above (mnemonic: begin) ;{pattern} perform another search, see
//;If a '-' or '+' is given but [num] is omitted, a count of one will be used.When including an offset with 'e', the search becomes inclusive (thecharacter the cursor lands on is included in operations).
Examples:
patterncursor position
/test/+1one line below "test", in column 1/test/eon the last t of "test"/test/s+2on the 's' of "test"/test/b-3three characters before "test"
If one of these commands is used after an operator, the characters betweenthe cursor position before and after the search is affected. However, if aline offset is given, the whole lines between the two cursor positions areaffected.
An example of how to search for matches with a pattern and change the matchwith another word:
/foo<CR>find "foo"c//e<CR>change until end of matchbar<Esc>type replacement//<CR>go to start of next matchc//e<CR>change until end of matchbeep<Esc>type another replacement etc.
//;E386A very special offset is ';' followed by another search command. For example:
/test 1/;/test/test.*/+1;?ing?
The first one first finds the next occurrence of "test 1", and then the firstoccurrence of "test" after that.
This is like executing two search commands after each other, except that:
It can be used as a single motion command after an operator.
The direction for a following "n" or "N" command comes from the first search command.
When an error occurs the cursor is not moved at all.
last-patternThe last used pattern and offset are remembered. They can be used to repeatthe search, possibly in another direction or with another count. Note thattwo patterns are remembered: One for "normal" search commands and one for thesubstitute command ":s". Each time an empty pattern is given, the previouslyused pattern is used. However, if there is no previous search command, aprevious substitute pattern is used, if possible.
The
'magic' option sticks with the last used pattern. If you change
'magic',this will not change how the last used pattern will be interpreted.The
'ignorecase' option does not do this. When
'ignorecase' is changed, itwill result in the pattern to match other text.
All matches for the last used search pattern will be highlighted if you setthe
'hlsearch' option.
To clear the last used search pattern:
:let @/ = ""
This will not set the pattern to an empty string, because that would matcheverywhere. The pattern is really cleared, like when starting Vim.
The search usually skips matches that don't move the cursor. Whether the nextmatch is found at the next character or after the skipped match depends on the'c' flag in
'cpoptions'. See
cpo-c. with 'c' flag: "/..." advances 1 to 3 characterswithout 'c' flag: "/..." advances 1 characterThe unpredictability with the 'c' flag is caused by starting the search in thefirst column, skipping matches until one is found past the cursor position.
When searching backwards, searching starts at the start of the line, using the'c' flag in
'cpoptions' as described above. Then the last match before thecursor position is used.
In Vi the ":tag" command sets the last search pattern when the tag is searchedfor. In Vim this is not done, the previous search pattern is stillremembered, unless the 't' flag is present in
'cpoptions'. The search patternis always put in the search history.
If the
'wrapscan' option is on (which is the default), searches wrap aroundthe end of the buffer. If
'wrapscan' is not set, the backward search stopsat the beginning and the forward search stops at the end of the buffer. If
'wrapscan' is set and the pattern was not found the error message "patternnot found" is given, and the cursor will not be moved. If
'wrapscan' is notset the message becomes "search hit BOTTOM without match" when searchingforward, or "search hit TOP without match" when searching backward. Ifwrapscan is set and the search wraps around the end of the file the message"search hit TOP, continuing at BOTTOM" or "search hit BOTTOM, continuing atTOP" is given when searching backwards or forwards respectively. This can beswitched off by setting the 's' flag in the
'shortmess' option. The highlightmethod 'w' is used for this message (default: standout).
search-rangeYou can limit the search command "/" to a certain range of lines by including\%>l items. For example, to match the word "limit" below line 199 and aboveline 300:
/\%>199l\%<300llimit
Also see
/\%>l.
Another way is to use the ":substitute" command with the 'c' flag. Example:
:.,300s/Pattern//gc
This command will search from the cursor position until line 300 for"Pattern". At the match, you will be asked to type a character. Type 'q' tostop at this match, type 'n' to find the next match.
The "*", "#", "g*" and "g#" commands look for a word near the cursor in thisorder, the first one that is found is used:
The keyword currently under the cursor.
The first keyword to the right of the cursor, in the same line.
The WORD currently under the cursor.
The first WORD to the right of the cursor, in the same line.The keyword may only contain letters and characters in
'iskeyword'.The WORD may contain any non-blanks (
<Tab>s and/or
<Space>s).Note that if you type with ten fingers, the characters are easy to remember:the "#" is under your left hand middle finger (search to the left and up) andthe "*" is under your right hand middle finger (search to the right and down).(this depends on your keyboard layout though).
E956In very rare cases a regular expression is used recursively. This can happenwhen executing a pattern takes a long time and when checking for messages onchannels a callback is invoked that also uses a pattern or an autocommand istriggered. In most cases this should be fine, but if a pattern is in use whenit's used again it fails. Usually this means there is something wrong withthe pattern.
For starters, read chapter 27 of the user manual
usr_27.txt.
/bar/\bar/pattern1. A pattern is one or more branches, separated by "\|". It matches anything that matches one of the branches. Example: "foo\|beep" matches "foo" and matches "beep". If more than one branch matches, the first one is used.
pattern ::= branchor branch \| branchor branch \| branch \| branchetc.
/branch/\&2. A branch is one or more concats, separated by "\&". It matches the last concat, but only if all the preceding concats also match at the same position. Examples:"foobeep\&..." matches "foo" in "foobeep".".*Peter\&.*Bob" matches in a line containing both "Peter" and "Bob"
branch ::= concator concat \& concator concat \& concat \& concatetc.
/concat3. A concat is one or more pieces, concatenated. It matches a match for the first piece, followed by a match for the second piece, etc. Example: "f[0-9]b", first matches "f", then a digit and then "b".
concat ::= pieceor piece pieceor piece piece pieceetc.
/piece4. A piece is an atom, possibly followed by a multi, an indication of how many times the atom can be matched. Example: "a*" matches any sequence of "a" characters: "", "a", "aa", etc. See
/multi.
piece ::= atomor atom multi
/atom5. An atom can be one of a long list of items. Many atoms match one character in the text. It is often an ordinary character or a character class. Parentheses can be used to make a pattern into an atom. The "\z(\)" construct is only for syntax highlighting.
/\%#=two-enginesNFAVim includes two regexp engines:1. An old, backtracking engine that supports everything.2. A new, NFA engine that works much faster on some patterns, possibly slower on some patterns.
E1281Vim will automatically select the right engine for you. However, if you runinto a problem or want to specifically select one engine or the other, you canprepend one of the following to the pattern:
\%#=0Force automatic selection. Only has an effect when
'regexpengine' has been set to a non-zero value.\%#=1Force using the old engine.\%#=2Force using the NFA engine.
E864E868E874E875E876E877E878If selecting the NFA engine and it runs into something that is not implementedthe pattern will not match. This is only useful when debugging Vim.
Some characters in the pattern, such as letters, are taken literally. Theymatch exactly the same character in the text. When preceded with a backslashhowever, these characters may get a special meaning. For example, "a" matchesthe letter "a", while "\a" matches any alphabetic character.
Other characters have a special meaning without a backslash. They need to bepreceded with a backslash to match literally. For example "." matches anycharacter while "\." matches a dot.
If a character is taken literally or not depends on the
'magic' option and theitems in the pattern mentioned next. The
'magic' option should always be set,but it can be switched off for Vi compatibility. We mention the effect of
'nomagic' here for completeness, but we recommend against using that.
/\m/\MUse of "\m" makes the pattern after it be interpreted as if
'magic' is set,ignoring the actual value of the
'magic' option.Use of "\M" makes the pattern after it be interpreted as if
'nomagic' is used.
/\v/\VUse of "\v" means that after it, all ASCII characters except '0'-'9', 'a'-'z','A'-'Z' and '_' have special meaning: "very magic"
Use of "\V" means that after it, only a backslash and the terminatingcharacter (usually / or ?) have special meaning: "very nomagic"
Examples:
after: \v \m \M \Vmatches
'magic''nomagic' a a a aliteral 'a' \a \a \a \aany alphabetic character . . \. \.any character \. \. . .literal dot $ $ $ \$end-of-line * * \* \*any number of the previous atom ~ ~ \~ \~latest substitute string () \(\) \(\) \(\)group as an atom | \| \| \|nothing: separates alternatives \\ \\ \\ \\literal backslash \{ { { {literal curly brace
If you want to you can make a pattern immune to the
'magic' option being setor not by putting "\m" or "\M" at the start of the pattern.
Overview of multi items.
/multiE61E62More explanation and examples below, follow the links.
E64E871multi
/star *\*0 or moreas many as possible
/\+ \+\+1 or moreas many as possible
/\= \=\=0 or 1as many as possible
/\? \?\?0 or 1as many as possible
/\{ \{n,m}\{n,m}n to mas many as possible\{n}\{n}nexactly\{n,}\{n,}at least nas many as possible\{,m}\{,m}0 to mas many as possible\{}\{}0 or moreas many as possible (same as "*")
/\{- \{-n,m}\{-n,m}n to mas few as possible\{-n}\{-n}nexactly\{-n,}\{-n,}at least nas few as possible\{-,m}\{-,m}0 to mas few as possible\{-}\{-}0 or moreas few as possible
Overview of ordinary atoms.
/ordinary-atomMore explanation and examples below, follow the links.
Character classes:
/character-classesmagic nomagicmatches
/\i \i\iidentifier character (see
'isident' option)
/\I \I\Ilike "\i", but excluding digits
/\k \k\kkeyword character (see
'iskeyword' option)
/\K \K\Klike "\k", but excluding digits
/\f \f\ffile name character (see
'isfname' option)
/\F \F\Flike "\f", but excluding digits
/\p \p\pprintable character (see
'isprint' option)
/\P \P\Plike "\p", but excluding digits
/\s \s\swhitespace character:
<Space> and
<Tab>/\S \S\Snon-whitespace character; opposite of \s
/\d \d\ddigit:[0-9]
/\D \D\Dnon-digit:[^0-9]
/\x \x\xhex digit:[0-9A-Fa-f]
/\X \X\Xnon-hex digit:[^0-9A-Fa-f]
/\o \o\ooctal digit:[0-7]
/\O \O\Onon-octal digit:[^0-7]
/\w \w\wword character:[0-9A-Za-z_]
/\W \W\Wnon-word character:[^0-9A-Za-z_]
/\h \h\hhead of word character:[A-Za-z_]
/\H \H\Hnon-head of word character:[^A-Za-z_]
/\a \a\aalphabetic character:[A-Za-z]
/\A \A\Anon-alphabetic character:[^A-Za-z]
/\l \l\llowercase character:[a-z]
/\L \L\Lnon-lowercase character:[^a-z]
/\u \u\uuppercase character:[A-Z]
/\U \U\Unon-uppercase character[^A-Z]
/\_ \_x\_xwhere x is any of the characters above: characterclass with end-of-line included(end of character classes)
magic nomagicmatches
/\e \e\e
<Esc>/\t \t\t
<Tab>/\r \r\r
<CR>/\b \b\b
<BS>/\n \n\nend-of-line
/~ ~\~last given substitute string
/\1 \1\1same string as matched by first \(\)
/\2 \2\2Like "\1", but uses second \(\) ...
/\9 \9\9Like "\1", but uses ninth \(\)
E68/\z1 \z1\z1only for syntax highlighting, see
:syn-ext-match ...
/\z1 \z9\z9only for syntax highlighting, see
:syn-ext-matchxxa character with no special meaning matches itself
/[] []\[]any character specified inside the []
/\%[] \%[]\%[]a sequence of optionally matched atoms
/\c \c\cignore case, do not use the
'ignorecase' option
/\C \C\Cmatch case, do not use the
'ignorecase' option
/\Z \Z\Zignore differences in Unicode "combining characters".Useful when searching voweled Hebrew or Arabic text.
magic nomagicmatches
/\m \m\m
'magic' on for the following chars in the pattern
/\M \M\M
'magic' off for the following chars in the pattern
/\v \v\vthe following chars in the pattern are "very magic"
/\V \V\Vthe following chars in the pattern are "very nomagic"
/\%#= \%#=1 \%#=1 select regexp engine
/zero-width/\%d \%d\%dmatch specified decimal character (eg \%d123)
/\%x \%x\%xmatch specified hex character (eg \%x2a)
/\%o \%o\%omatch specified octal character (eg \%o040)
/\%u \%u\%umatch specified multibyte character (eg \%u20ac)
/\%U \%U\%Umatch specified large multibyte character (eg\%U12345678)
/\%C \%C\%Cmatch any composing characters
Examplematches
\<\I\i*or\<\h\w*\<[a-zA-Z_][a-zA-Z0-9_]*An identifier (e.g., in a C program).
\(\.$\|\. \)A period followed by<EOL> or a space.
[.!?][])"']*\($\|[ ]\)A search pattern that finds the end of a sentence,with almost the same definition as the ")" command.
cat\ZBoth "cat" and "càt" ("a" followed by 0x0300)Does not match "càt" (character 0x00e0), eventhough it may look the same.
An atom can be followed by an indication of how many times the atom can bematched and in what way. This is called a multi. See
/multi for anoverview.
/star/\star*(use \* when
'magic' is not set)Matches 0 or more of the preceding atom, as many as possible.
a* a\*"", "a", "aa", "aaa", etc..* \.\*anything, also an empty string, no end-of-line\_.* \_.\*everything up to the end of the buffer\_.*END \_.\*ENDeverything up to and including the last "END"in the buffer
Exception: When "*" is used at the start of the pattern or just after"^" it matches the star character.
Be aware that repeating "\_." can match a lot of text and take a longtime. For example, "\_.*END" matches all text from the currentposition to the last occurrence of "END" in the file. Since the "*"will match as many as possible, this first skips over all lines untilthe end of the file and then tries matching "END", backing up onecharacter at a time.
/\+\+Matches 1 or more of the preceding atom, as many as possible.
Examplematches
^.\+$any non-empty line\s\+white space of at least one character
/\=\=Matches 0 or 1 of the preceding atom, as many as possible.
Examplematches
foo\="fo" and "foo"
/\?\?Just like \=. Cannot be used when searching backwards with the "?"command.
/\{E60E554E870\{n,m}Matches n to m of the preceding atom, as many as possible\{n}Matches n of the preceding atom\{n,}Matches at least n of the preceding atom, as many as possible\{,m}Matches 0 to m of the preceding atom, as many as possible\{}Matches 0 or more of the preceding atom, as many as possible (like "*")
/\{-\{-n,m}matches n to m of the preceding atom, as few as possible\{-n}matches n of the preceding atom\{-n,}matches at least n of the preceding atom, as few as possible\{-,m}matches 0 to m of the preceding atom, as few as possible\{-}matches 0 or more of the preceding atom, as few as possible
n and m are positive decimal numbers or zero
non-greedyIf a "-" appears immediately after the "{", then a shortest matchfirst algorithm is used (see example below). In particular, "\{-}" isthe same as "*" but uses the shortest match first algorithm. BUT: Amatch that starts earlier is preferred over a shorter match: "a\{-}b"matches "aaab" in "xaaab".
Examplematches
ab\{2,3}c"abbc" or "abbbc"a\{5}"aaaaa"ab\{2,}c"abbc", "abbbc", "abbbbc", etc.ab\{,3}c"ac", "abc", "abbc" or "abbbc"a[bc]\{3}d"abbbd", "abbcd", "acbcd", "acccd", etc.a\(bc\)\{1,2}d"abcd" or "abcbcd"a[bc]\{-}[cd]"abc" in "abcd"a[bc]*[cd]"abcd" in "abcd"
The } may optionally be preceded with a backslash: \{n,m\}.
/\@=\@=Matches the preceding atom with zero width.Like "(?=pattern)" in Perl.
Examplematches
foo\(bar\)\@="foo" in "foobar"foo\(bar\)\@=foonothing
/zero-widthWhen using "\@=" (or "^", "$", "\<", "\>") no characters are includedin the match. These items are only used to check if a match can bemade. This can be tricky, because a match with following items willbe done in the same position. The last example above will not match"foobarfoo", because it tries match "foo" in the same position where"bar" matched.
Note that using "\&" works the same as using "\@=": "foo\&.." is thesame as "\(foo\)\@=..". But using "\&" is easier, you don't need theparentheses.
/\@!\@!Matches with zero width if the preceding atom does NOT match at thecurrent position.
/zero-widthLike "(?!pattern)" in Perl.
Examplematches
foo\(bar\)\@!any "foo" not followed by "bar"a.\{-}p\@!"a", "ap", "app", "appp", etc. not immediatelyfollowed by a "p"if \(\(then\)\@!.\)*$"if " not followed by "then"
Using "\@!" is tricky, because there are many places where a patterndoes not match. "a.*p\@!" will match from an "a" to the end of theline, because ".*" can match all characters in the line and the "p"doesn't match at the end of the line. "a.\{-}p\@!" will match any"a", "ap", "app", etc. that isn't followed by a "p", because the "."can match a "p" and "p\@!" doesn't match after that.
You can't use "\@!" to look for a non-match before the matchingposition: "\(foo\)\@!bar" will match "bar" in "foobar", because at theposition where "bar" matches, "foo" does not match. To avoid matching"foobar" you could use "\(foo\)\@!...bar", but that doesn't match abar at the start of a line. Use "\(foo\)\@<!bar".
Useful example: to find "foo" in a line that does not contain "bar":
/^\%(.*bar\)\@!.*\zsfoo
This pattern first checks that there is not a single position in theline where "bar" matches. If ".*bar" matches somewhere the \@! willreject the pattern. When there is no match any "foo" will be found.The "\zs" is to have the match start just before "foo".
/\@<=\@<=Matches with zero width if the preceding atom matches just before whatfollows.
/zero-widthLike "(?<=pattern)" in Perl, but Vim allows non-fixed-width patterns.
Examplematches
\(an\_s\+\)\@<=file"file" after "an" and white space or anend-of-lineFor speed it's often much better to avoid this multi. Try using "\zs"instead
/\zs. To match the same as the above example:an\_s\+\zsfileAt least set a limit for the look-behind, see below.
"\@<=" and "\@<!" check for matches just before what follows.Theoretically these matches could start anywhere before this position.But to limit the time needed, only the line where what follows matchesis searched, and one line before that (if there is one). This shouldbe sufficient to match most things and not be too slow.
In the old regexp engine the part of the pattern after "\@<=" and"\@<!" are checked for a match first, thus things like "\1" don't workto reference \(\) inside the preceding atom. It does work the otherway around:
Bad examplematches
\%#=1\1\@<=,\([a-z]\+\)",abc" in "abc,abc"
However, the new regexp engine works differently, it is better to notrely on this behavior, do not use \@<= if it can be avoided:
Examplematches
\([a-z]\+\)\zs,\1",abc" in "abc,abc"
\@123<=Like "\@<=" but only look back 123 bytes. This avoids trying lotsof matches that are known to fail and make executing the pattern veryslow. Example, check if there is a "<" just before "span":/<\@1<=spanThis will try matching "<" only one byte before "span", which is theonly place that works anyway.After crossing a line boundary, the limit is relative to the end ofthe line. Thus the characters at the start of the line with the matchare not counted (this is just to keep it simple).The number zero is the same as no limit.
/\@<!\@<!Matches with zero width if the preceding atom does NOT match justbefore what follows. Thus this matches if there is no position in thecurrent or previous line where the atom matches such that it ends justbefore what follows.
/zero-widthLike "(?<!pattern)" in Perl, but Vim allows non-fixed-width patterns.The match with the preceding atom is made to end just before the matchwith what follows, thus an atom that ends in ".*" will work.
Warning: This can be slow (because many positions need to be checkedfor a match). Use a limit if you can, see below.
Examplematches
\(foo\)\@<!barany "bar" that's not in "foobar"\(\/\/.*\)\@<!in"in" which is not after "//"
\@123<!Like "\@<!" but only look back 123 bytes. This avoids trying lots ofmatches that are known to fail and make executing the pattern veryslow.
/\@>\@>Matches the preceding atom like matching a whole pattern.Like "(?>pattern)" in Perl.
Examplematches
\(a*\)\@>anothing (the "a*" takes all the "a"'s, there can't beanother one following)
This matches the preceding atom as if it was a pattern by itself. Ifit doesn't match, there is no retry with shorter sub-matches oranything. Observe this difference: "a*b" and "a*ab" both match"aaab", but in the second case the "a*" matches only the first two"a"s. "\(a*\)\@>ab" will not match "aaab", because the "a*" matchesthe "aaa" (as many "a"s as possible), thus the "ab" can't match.
An ordinary atom can be:
/^^At beginning of pattern or after "\|", "\(", "\%(" or "\n": matchesstart-of-line; at other positions, matches literal '^'.
/zero-widthExamplematches
^beep(the start of the C function "beep" (probably).
/\^\^Matches literal '^'. Can be used at any position in the pattern, butnot inside [].
/\_^\_^Matches start-of-line.
/zero-width Can be used at any position inthe pattern, but not inside [].
Examplematches
\_s*\_^foowhite space and blank lines and then "foo" atstart-of-line
/$$At end of pattern or in front of "\|", "\)" or "\n" (
'magic' on):matches end-of-line
<EOL>; at other positions, matches literal '$'.
/zero-width /\$\$Matches literal '$'. Can be used at any position in the pattern, butnot inside [].
/\_$\_$Matches end-of-line.
/zero-width Can be used at any position in thepattern, but not inside []. Note that "a\_$b" never matches, since"b" cannot match an end-of-line. Use "a\nb" instead
/\n.
Examplematches
foo\_$\_s*"foo" at end-of-line and following white space andblank lines
.(with
'nomagic': \.)
/./\.Matches any single character, but not an end-of-line.
/\_.\_.Matches any single character or end-of-line.Careful: "\_.*" matches all text to the end of the buffer!
/\<\<Matches the beginning of a word: The next char is the first char of aword. The
'iskeyword' option specifies what is a word character.
/zero-width /\>\>Matches the end of a word: The previous char is the last char of aword. The
'iskeyword' option specifies what is a word character.
/zero-width /\zs\zsMatches at any position, but not inside [], and sets the start of thematch there: The next char is the first char of the whole match.
/zero-width Example:
/^\s*\zsif
matches an "if" at the start of a line, ignoring white space.Can be used multiple times, the last one encountered in a matchingbranch is used. Example:
/\(.\{-}\zsFab\)\{3}Finds the third occurrence of "Fab".This cannot be followed by a multi.
E888/\ze\zeMatches at any position, but not inside [], and sets the end of thematch there: The previous char is the last char of the whole match.
/zero-width Can be used multiple times, the last one encountered in a matchingbranch is used.Example: "end\ze\(if\|for\)" matches the "end" in "endif" and"endfor".This cannot be followed by a multi.
E888 /\%^start-of-file\%^Matches start of the file. When matching with a string, matches thestart of the string.For example, to find the first "VIM" in a file:
/\%^\_.\{-}\zsVIM /\%$end-of-file\%$Matches end of the file. When matching with a string, matches theend of the string.Note that this does NOT find the last "VIM" in a file:
/VIM\_.\{-}\%$ It will find the next VIM, because the part after it will alwaysmatch. This one will find the last "VIM" in the file:
/VIM\ze\(\(VIM\)\@!\_.\)*\%$
This uses
/\@! to ascertain that "VIM" does NOT match in anyposition after the first "VIM".Searching from the end of the file backwards is easier!
/\%V\%VMatch inside the Visual area. When Visual mode has already beenstopped match in the area that
gv would reselect.This is a
/zero-width match. To make sure the whole pattern isinside the Visual area put it at the start and just before the end ofthe pattern, e.g.:
/\%Vfoo.*ba\%Vr
This also works if only "foo bar" was Visually selected. This:
/\%Vfoo.*bar\%V
would match "foo bar" if the Visual selection continues after the "r".Only works for the current buffer.
/\%#cursor-position\%#Matches with the cursor position. Only works when matching in abuffer displayed in a window.
WARNING: When the cursor is moved after the pattern was used, theresult becomes invalid. Vim doesn't automatically update the matches.This is especially relevant for syntax highlighting and
'hlsearch'.In other words: When the cursor moves the display isn't updated forthis change. An update is done for lines which are changed (the wholeline is updated) or when using the
CTRL-L command (the whole screenis updated). Example, to highlight the word under the cursor:
/\k*\%#\k*
When
'hlsearch' is set and you move the cursor around and make changesthis will clearly show when the match is updated or not.
/\%'m/\%<'m/\%>'m\%'mMatches with the position of mark m.\%<'mMatches before the position of mark m.\%>'mMatches after the position of mark m.Example, to highlight the text from mark 's to 'e:
/.\%>'s.*\%<'e..
Note that two dots are required to include mark 'e in the match. Thatis because "\%<'e" matches at the character before the 'e mark, andsince it's a
/zero-width match it doesn't include that character.
WARNING: When the mark is moved after the pattern was used, the resultbecomes invalid. Vim doesn't automatically update the matches.Similar to moving the cursor for "\%#"
/\%#.
/\%l/\%>l/\%<lE951E1204\%23lMatches in a specific line.\%<23lMatches above a specific line (lower line number).\%>23lMatches below a specific line (higher line number).\%.lMatches at the cursor line.\%<.lMatches above the cursor line.\%>.lMatches below the cursor line.These six can be used to match specific lines in a buffer. The "23"can be any line number. The first line is 1.
WARNING: When inserting or deleting lines Vim does not automaticallyupdate the matches. This means Syntax highlighting quickly becomeswrong. Also when referring to the cursor position (".") andthe cursor moves the display isn't updated for this change. An updateis done when using the
CTRL-L command (the whole screen is updated).Example, to highlight the line where the cursor currently is:
:exe '/\%' .. line(".") .. 'l' When
'hlsearch' is set and you move the cursor around and make changesthis will clearly show when the match is updated or not.
/\%c/\%>c/\%<c\%23cMatches in a specific column.\%<23cMatches before a specific column.\%>23cMatches after a specific column.\%.cMatches at the cursor column.\%<.cMatches before the cursor column.\%>.cMatches after the cursor column.These six can be used to match specific columns in a buffer or string.The "23" can be any column number. The first column is 1. Actually,the column is the byte number (thus it's not exactly right formultibyte characters).
WARNING: When inserting or deleting text Vim does not automaticallyupdate the matches. This means Syntax highlighting quickly becomeswrong. Also when referring to the cursor position (".") andthe cursor moves the display isn't updated for this change. An updateis done when using the
CTRL-L command (the whole screen is updated).Example, to highlight the column where the cursor currently is:
:exe '/\%' .. col(".") .. 'c' When
'hlsearch' is set and you move the cursor around and make changesthis will clearly show when the match is updated or not.Example for matching a single byte in column 44:
/\%>43c.\%<46c
Note that "\%<46c" matches in column 45 when the "." matches a byte incolumn 44.
/\%v/\%>v/\%<v\%23vMatches in a specific virtual column.\%<23vMatches before a specific virtual column.\%>23vMatches after a specific virtual column.\%.vMatches at the current virtual column.\%<.vMatches before the current virtual column.\%>.vMatches after the current virtual column.These six can be used to match specific virtual columns in a buffer orstring. When not matching with a buffer in a window, the optionvalues of the current window are used (e.g.,
'tabstop').The "23" can be any column number. The first column is 1.Note that some virtual column positions will never match, because theyare halfway through a tab or other character that occupies more thanone screen character.
WARNING: When inserting or deleting text Vim does not automaticallyupdate highlighted matches. This means Syntax highlighting quicklybecomes wrong. Also when referring to the cursor position (".") andthe cursor moves the display isn't updated for this change. An updateis done when using the
CTRL-L command (the whole screen is updated).Example, to highlight all the characters after virtual column 72:
/\%>72v.*
When
'hlsearch' is set and you move the cursor around and make changesthis will clearly show when the match is updated or not.To match the text up to column 17:
/^.*\%17v
To match all characters after the current virtual column (where thecursor is):
/\%>.v.*
Column 17 is not included, because this is a
/zero-width match. Toinclude the column use:
/^.*\%17v.
This command does the same thing, but also matches when there is nocharacter in column 17:
/^.*\%<18v.
Note that without the "^" to anchor the match in the first column,this will also highlight column 17:
/.*\%17v
Column 17 is highlighted by
'hlsearch' because there is another matchwhere ".*" matches zero characters.
Character classes:\iidentifier character (see
'isident' option)
/\i \Ilike "\i", but excluding digits
/\I\kkeyword character (see
'iskeyword' option)
/\k \Klike "\k", but excluding digits
/\K\ffile name character (see
'isfname' option)
/\f \Flike "\f", but excluding digits
/\F\pprintable character (see
'isprint' option)
/\p \Plike "\p", but excluding digits
/\PNOTE: the above also work for multibyte characters. The ones below onlymatch ASCII characters, as indicated by the range.
whitespacewhite-space\swhitespace character:
<Space> and
<Tab>/\s\Snon-whitespace character; opposite of \s
/\S \ddigit:[0-9]
/\d\Dnon-digit:[^0-9]
/\D\xhex digit:[0-9A-Fa-f]
/\x \Xnon-hex digit:[^0-9A-Fa-f]
/\X \ooctal digit:[0-7]
/\o\Onon-octal digit:[^0-7]
/\O\wword character:[0-9A-Za-z_]
/\w \Wnon-word character:[^0-9A-Za-z_]
/\W \hhead of word character:[A-Za-z_]
/\h \Hnon-head of word character:[^A-Za-z_]
/\H \aalphabetic character:[A-Za-z]
/\a \Anon-alphabetic character:[^A-Za-z]
/\A \llowercase character:[a-z]
/\l\Lnon-lowercase character:[^a-z]
/\L\uuppercase character:[A-Z]
/\u\Unon-uppercase character:[^A-Z]
/\U NOTE: Using the atom is faster than the [] form.
NOTE:'ignorecase', "\c" and "\C" are not used by character classes.
\ematches
<Esc>/\e\tmatches
<Tab>/\t\rmatches
<CR>/\r\bmatches
<BS>/\b\nmatches an end-of-line
/\nWhen matching in a string instead of buffer text a literal newlinecharacter is matched.
~matches the last given substitute string
/~/\~\(\)A pattern enclosed by escaped parentheses.
/\(/\(\)/\)E.g., "\(^a\)" matches 'a' at the start of a line.There can only be nine of these. You can use "\%(" to add more, butnot counting it as a sub-expression.
E51E54E55E872E873\1 Matches the same string that was matched by
/\1E65the first sub-expression in \( and \).Example: "\([a-z]\).\1" matches "ata", "ehe", "tot", etc.\2 Like "\1", but uses second sub-expression,
/\2 ...
/\3\9 Like "\1", but uses ninth sub-expression.
/\9Note: The numbering of groups is done based on which "\(" comes firstin the pattern (going left to right), NOT based on what is matchedfirst.
\%(\)A pattern enclosed by escaped parentheses.
/\%(\)/\%(E53Just like \(\), but without counting it as a sub-expression. Thisallows using more groups and it's a little bit faster.
xA single character, with no special meaning, matches itself
/\/\\\xA backslash followed by a single character, with no special meaning,is reserved for future expansions
[](with
'nomagic': \[])
/[]/\[]/\_[]/collectionE76\_[]A collection. This is a sequence of characters enclosed in squarebrackets. It matches any single character in the collection.
Examplematches
[xyz]any 'x', 'y' or 'z'[a-zA-Z]$any alphabetic character at the end of a line\c[a-z]$same[А-яЁё]Russian alphabet (with utf-8 and cp1251)
/[\n]With "\_" prepended the collection also includes the end-of-line.The same can be done by including "\n" in the collection. Theend-of-line is also matched when the collection starts with "^"! Thus"\_[^ab]" matches the end-of-line and any character but "a" and "b".This makes it Vi compatible: Without the "\_" or "\n" the collectiondoes not match an end-of-line.
E769When the ']' is not there Vim will not give an error message butassume no collection is used. Useful to search for '['. However, youdo get E769 for internal searching. And be aware that in a
:substitute command the whole command becomes the pattern. E.g.":s/[/x/" searches for "[/x" and replaces it with nothing. It doesnot search for "[" and replaces it with "x"!
E944E945If the sequence begins with "^", it matches any single character NOTin the collection: "[^xyz]" matches anything but 'x', 'y' and 'z'.
If two characters in the sequence are separated by '-', this is shorthand for the full list of ASCII characters between them. E.g., "[0-9]" matches any decimal digit. If the starting character exceeds the ending character, e.g. [c-a], E944 occurs. Non-ASCII characters can be used, but the character values must not be more than 256 apart in the old regexp engine. For example, searching by [\u3000-\u4000] after setting re=1 emits a E945 error. Prepending \%#=2 will fix it.
A character class expression is evaluated to the set of characters belonging to that character class. The following character classes are supported: Name FuncContents ~
[:alnum:] [:alnum:] isalnumASCII letters and digits
[:alpha:] [:alpha:] isalphaASCII letters
[:blank:] [:blank:]space and tab
[:cntrl:] [:cntrl:] iscntrlASCII control characters
[:digit:] [:digit:]decimal digits '0' to '9'
[:graph:] [:graph:] isgraphASCII printable characters excludingspace
[:lower:] [:lower:] (1)lowercase letters (all letters when
'ignorecase' is used)
[:print:] [:print:] (2)printable characters including space
[:punct:] [:punct:] ispunctASCII punctuation characters
[:space:] [:space:]whitespace characters: space, tab, CR,NL, vertical tab, form feed
[:upper:] [:upper:] (3)uppercase letters (all letters when
'ignorecase' is used)
[:xdigit:] [:xdigit:]hexadecimal digits: 0-9, a-f, A-F
[:return:] [:return:]the
<CR> character
[:tab:] [:tab:]the
<Tab> character
[:escape:] [:escape:]the
<Esc> character
[:backspace:] [:backspace:]the
<BS> character
[:ident:] [:ident:]identifier character (same as "\i")
[:keyword:] [:keyword:]keyword character (same as "\k")
[:fname:] [:fname:]file name character (same as "\f") The square brackets in character class expressions are additional to the square brackets delimiting a collection. For example, the following is a plausible pattern for a UNIX filename: "[-./[:alnum:]_~]\+". That is, a list of at least one character, each of which is either '-', '.', '/', alphabetic, numeric, '_' or '~'. These items only work for 8-bit characters, except [:lower:] and [:upper:] also work for multibyte characters when using the new regexp engine. See
two-engines. In the future these items may work for multibyte characters. For now, to get all "alpha" characters you can use: [[:lower:][:upper:]].
The "Func" column shows what library function is used. The implementation depends on the system. Otherwise: (1) Uses islower() for ASCII and Vim builtin rules for other characters. (2) Uses Vim builtin rules (3) As with (1) but using isupper()
/[[=[==] An equivalence class. This means that characters are matched that have almost the same meaning, e.g., when ignoring accents. This only works for Unicode, latin1 and latin9. The form is:[=a=]
/[[.[..] A collation element. This currently simply accepts a single character in the form:[.a.]
/\] To include a literal ']', '^', '-' or '\' in the collection, put a backslash before it: "[xyz\]]", "[\^xyz]", "[xy\-z]" and "[xyz\\]". (Note: POSIX does not support the use of a backslash this way). For ']' you can also make it the first character (following a possible "^"): "[]xyz]" or "[^]xyz]". For '-' you can also make it the first or last character: "[-xyz]", "[^-xyz]" or "[xyz-]". For '\' you can also let it be followed by any character that's not in "^]-\bdertnoUux". "[\xyz]" matches '\', 'x', 'y' and 'z'. It's better to use "\\" though, future expansions may use other characters after '\'.
Omitting the trailing ] is not considered an error. "[]" works like "[]]", it matches the ']' character.
The following translations are accepted when the 'l' flag is not included in
'cpoptions':\e
<Esc>\t
<Tab>\r
<CR>(NOT end-of-line!)\b
<BS>\nline break, see above
/[\n]\d123decimal number of character\o40octal number of character up to 0o377\x20hexadecimal number of character up to 0xff\u20AChex. number of multibyte character up to 0xffff\U1234hex. number of multibyte character up to 8 characters0xffffffff
E1541 NOTE: The other backslash codes mentioned above do not work inside []!
Matching with a collection can be slow, because each character in the text has to be compared with each character in the collection. Use one of the other atoms above when possible. Example: "\d" is much faster than "[0-9]" and matches the same characters. However, the new
NFA regexp engine deals with this better than the old one.
/\%[]E69E70E369\%[]A sequence of optionally matched atoms. This always matches.It matches as much of the list of atoms it contains as possible. Thusit stops at the first atom that doesn't match. For example:
/r\%[ead]
matches "r", "re", "rea" or "read". The longest that matches is used.To match the Ex command "function", where "fu" is required and"nction" is optional, this would work:
/\<fu\%[nction]\>
The end-of-word atom "\>" is used to avoid matching "fu" in "full".It gets more complicated when the atoms are not ordinary characters.You don't often have to use it, but it is possible. Example:
/\<r\%[[eo]ad]\>
Matches the words "r", "re", "ro", "rea", "roa", "read" and "road".There can be no \(\), \%(\) or \z(\) items inside the [] and \%[] doesnot nest.To include a "[" use "[[]" and for "]" use []]", e.g.,:
/index\%[[[]0[]]]
matches "index" "index[", "index[0" and "index[0]".
\%d123Matches the character specified with a decimal number. Must befollowed by a non-digit.\%o40Matches the character specified with an octal number up to 0o377.Numbers below 0o40 must be followed by a non-octal digit or anon-digit.\%x2aMatches the character specified with up to two hexadecimal characters.\%u20ACMatches the character specified with up to four hexadecimalcharacters.\%U1234abcdMatches the character specified with up to eight hexadecimalcharacters, up to 0x7fffffff (the maximum allowed value is INT_MAX
E1541, but the maximum valid Unicode codepoint is U+10FFFF).
If the
'ignorecase' option is on, the case of normal letters is ignored.
'smartcase' can be set to ignore case when the pattern contains lowercaseletters only.
/\c/\CWhen "\c" appears anywhere in the pattern, the whole pattern is handled like
'ignorecase' is on. The actual value of
'ignorecase' and
'smartcase' isignored. "\C" does the opposite: Force matching case for the whole pattern.Note that
'ignorecase', "\c" and "\C" are not used for the character classes.
Examples:
foo off-foofoo on-foo Foo FOOFoo onofffoo Foo FOOFoo onon Foo\cfoo --foo Foo FOOfoo\C --foo
Technical detail:
NL-used-for-Nul<Nul> characters in the file are stored as
<NL> in memory. In the displaythey are shown as "^@". The translation is done when reading and writingfiles. To match a
<Nul> with a search pattern you can just enter
CTRL-@ or"CTRL-V 000". This is probably just what you expect. Internally thecharacter is replaced with a
<NL> in the search pattern. What is unusual isthat typing
CTRL-VCTRL-J also inserts a
<NL>, thus also searches for a
<Nul>in the file.
CR-used-for-NLWhen
'fileformat' is "mac",
<NL> characters in the file are stored as
<CR>characters internally. In the text they are shown as "^J". Otherwise thisworks similar to the usage of
<NL> for a
<Nul>.
When working with expression evaluation, a<NL> character in the patternmatches a<NL> in the string. The use of "\n" (backslash n) to match a<NL>doesn't work there, it only works to match text in the buffer.
pattern-multi-bytepattern-multibytePatterns will also work with multibyte characters, mostly as you wouldexpect. But invalid bytes may cause trouble, a pattern with an invalid bytewill probably never match.
/\ZWhen "\Z" appears anywhere in the pattern, all composing characters areignored. Thus only the base characters need to match, the composingcharacters may be different and the number of composing characters may differ.Exception: If the pattern starts with one or more composing characters, thesemust match.
/\%CUse "\%C" to skip any composing characters. For example, the pattern "a" doesnot match in "càt" (where the a has the composing character 0x0300), but"a\%C" does. Note that this does not match "cát" (where the á is character0xe1, it does not have a compositing character). It does match "cat" (wherethe a is just an a).
When a composing character appears at the start of the pattern or after anitem that doesn't include the composing character, a match is found at anycharacter that includes this composing character.
When using a dot and a composing character, this works the same as thecomposing character by itself, except that it doesn't matter what comes beforethis.
The order of composing characters does not matter. Also, the text may havemore composing characters than the pattern, it still matches. But allcomposing characters in the pattern must be found in the text.
Suppose B is a base character and x and y are composing characters:
patterntextmatch
BxyBxyyes (perfect match)BxyByxyes (order ignored)BxyByno (x missing)BxyBxno (y missing)BxBxyes (perfect match)BxByno (x missing)BxBxyyes (extra y ignored)BxByxyes (extra y ignored)
Vim's regexes are most similar to Perl's, in terms of what you can do. Thedifference between them is mostly just notation; here's a summary of wherethey differ:
Capabilityin Vimspeakin Perlspeak
force case insensitivity\c(?i)force case sensitivity\C(?-i)backref-less grouping\%(atom\)(?:atom)conservative quantifiers\{-n,m}
*?, +?, ??, {}?0-width matchatom\@=(?=atom)0-width non-matchatom\@!(?!atom)0-width preceding matchatom\@<=(?<=atom)0-width preceding non-matchatom\@<!(?<!atom)match without retryatom\@>(?>atom)
Vim and Perl handle newline characters inside a string a bit differently:
In Perl, ^ and $ only match at the very beginning and end of the text,by default, but you can set the 'm' flag, which lets them match atembedded newlines as well. You can also set the 's' flag, which causesa . to match newlines as well. (Both these flags can be changed insidea pattern using the same syntax used for the i flag above, BTW.)
On the other hand, Vim's ^ and $ always match at embedded newlines, andyou get two separate atoms, \%^ and \%$, which only match at the verystart and end of the text, respectively. Vim solves the second problemby giving you the \_ "modifier": put it in front of a . or a characterclass, and they will match newlines as well.
Finally, these constructs are unique to Perl:
execution of arbitrary code in the regex: (?{perl code})
conditional expressions: (?(condition)true-expr|false-expr)
...and these are unique to Vim:
changing the magic-ness of a pattern: \v \V \m \M (very useful for avoiding backslashitis)
sequence of optionally matching atoms: \%[atoms]
\& (which is to \| what "and" is to "or"; it forces several branches to match at one spot)
matching lines/columns by number: \%5l \%5c \%5v
setting the start and end of the match: \zs \ze
syntax-vs-matchNote that the match highlight mechanism is independentof
syntax-highlighting, which is (usually) a buffer-localhighlighting, while matching is window-local, both methodscan be freely mixed. Match highlighting functions give youa bit more flexibility in when and how to apply, but aretypically only used for temporary highlighting, without strictrules. Both methods can be used to conceal text.
Thus the matching functions like
matchadd() won't considersyntax rules and functions like
synconcealed() and theother way around.
:mat:match:mat[ch]
{group} /{pattern}/Define a pattern to highlight in the current window. It willbe highlighted with
{group}. Example:
:highlight MyGroup ctermbg=green guibg=green:match MyGroup /TODO/
Instead of // any character can be used to mark the start andend of the{pattern}. Watch out for using special characters,such as '"' and '|'.
{group} must exist at the moment this command is executed.
The
{group} highlighting still applies when a character isto be highlighted for
'hlsearch', as the highlighting formatches is given higher priority than that of
'hlsearch'.Syntax highlighting (see
'syntax') is also overruled bymatches.
Note that highlighting the last used search pattern with
'hlsearch' is used in all windows, while the pattern definedwith ":match" only exists in the current window. It is keptwhen switching to another buffer.
'ignorecase' does not apply, use
/\c in the pattern toignore case. Otherwise case is not ignored.
'redrawtime' defines the maximum time searched for patternmatches.
When matching end-of-line and Vim redraws only part of thedisplay you may get unexpected results. That is because Vimlooks for a match in the line where redrawing starts.
Highlighting matches using
:match are limited to threematches (aside from
:match,
:2match and
:3match areavailable).
matchadd() does not have this limitation and inaddition makes it possible to prioritize matches.
Another example, which highlights all characters in virtualcolumn 72 and more:
:highlight rightMargin term=bold ctermfg=blue guifg=blue:match rightMargin /.\%>72v/
To highlight all character that are in virtual column 7:
:highlight col8 ctermbg=grey guibg=grey:match col8 /\%<8v.\%>7v/
Note the use of two items to also match a character thatoccupies more than one virtual column, such as a TAB.
:mat[ch]:mat[ch] noneClear a previously defined match pattern.
:2mat[ch]
{group} /{pattern}/
:2match:2mat[ch]:2mat[ch] none:3mat[ch]
{group} /{pattern}/
:3match:3mat[ch]:3mat[ch] noneJust like
:match above, but set a separate match. Thusthere can be three matches active at the same time. The matchwith the lowest number has priority if several match at thesame position. It uses the match id 3.The ":3match" command is used by (older Vims)
matchparenplugin. You are suggested to use ":match" for manual matchingand ":2match" for another plugin or even better make use ofthe more flexible
matchadd() (and similar) functions instead.
Fuzzy matching scores how well a string matches a pattern when the patterncharacters appear in order but not necessarily contiguously.
Example:
Pattern:"vim"Candidates:"vim" -> perfect "vimeo" -> good (v i m) "voice mail" -> weaker (v _ i _ _ _ m) "vintage" -> no match (no "m")
If the search string has multiple words, each word is matched separately andmay appear in any order in the candidate. For example "get pat" matches"GetPattern", "PatternGet", "getPattern", "patGetter", "getSomePattern","MatchpatternGet", etc.
It uses dynamic programming to compute an optimal score for a given patternand candidate.
The algorithm works in two stages:
1. Forward pass Scan the candidate left to right, tracking the best score for each pattern position. Matches score higher when they occur at the start of the candidate, the start of a word (space, underscore, dash, camelCase), or directly after the previous match.
2. Backward pass Start from the best-scoring end position and step back to find match positions, ensuring the alignment is optimal.
Vim extends the original algorithm to support multibyte codepoints, allowingcorrect matching for UTF-8 and other encodings.
Time complexity is O(pattern * candidate). Memory usage is proportionalto the same.
The "f" flag of:vimgrep enables fuzzy matching.