bigTree
bigTree

Reputation: 2183

Finding exact match in Vim

Using / or ? enables to find a match for a word in Vim. But how can I find an exact match?

For example, my text contains the following words: a aa aaa aaaa aa and I type /aa. This will find all the strings containing the pattern aa, but what if I want to find exactly aa and not aaaa aaaa?

Upvotes: 25

Views: 34612

Answers (5)

Suresh
Suresh

Reputation: 21

This simple one helped me to match the exact pattern. You can try this.

\V\c\<pattern_here\>

Upvotes: 2

Ingo Karkat
Ingo Karkat

Reputation: 172788

To find a single, standalone aa (not a, aaa, ...), you need to assert no match of that character both before and afterwards. This is done with negative lookbehind (\@<! in Vim's regular expression syntax) and lookahead (\@!) enclosing the match itself (a\{2}):

/\%(a\)\@<!a\{2}\%(a\)\@!/

Simplification

Those assertions are hard to type, if the border around the match is also a non-keyword / keyword border, you can use the shorter \<\a\{2}\> assertions (as in LSchueler's answer), but this doesn't work in the general case, e.g. with xaax.

Upvotes: 10

motepc
motepc

Reputation: 31

Bring your cursor to exact word which you want to search.

Press * (Either Shitf+8 or from numpad of keybord).

Upvotes: 1

Yawar
Yawar

Reputation: 11637

You can search for aa[^a], which will find your two as and nothing else.

EDIT: oh boy, y'all are after an exact match :-) So, to match exactly two aas and nothing else:

[^a]\zsaa\ze[^a]\|^\zsaa\ze$\|^\zsaa\ze[^a]\|[^a]\zsaa\ze$

And the branches expanded out:

  [^a]\zsaa\ze[^a]
\|^\zsaa\ze$
\|^\zsaa\ze[^a]
\|[^a]\zsaa\ze$

These cover all contingencies--the aas can be at the beginning, the middle, or the end of any line. And there can't be more than two as together.

  • \zs means the actual match starts here
  • \ze means the actual match ends here
  • the first branch finds aa in a line surrounded by other characters
  • the second branch finds aa when it makes up the whole line
  • the third branch finds aa at the beginning of a line
  • and the fourth branch finds aa at the end of a line.

My mind boggles at fancy things like look-behind assertions, so I tried to stick to reasonably simple regex concepts.

EDIT 2: see @benjifisher's simplified, more elegant version below for your intellectual pleasure.

Upvotes: 2

LSchueler
LSchueler

Reputation: 1524

You enclose the string you are looking for by \< and \> like in /\<aa\> to match exactly that string.

Upvotes: 50

Related Questions