Finding an exact match in vim

Use / or ? allows you 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 lines containing the aa pattern, but what if I want to find exactly aa , not aaaa aaaa ?

+8
source share
4 answers

In order to find one, standalone aa (not, a aaa , ...), you need not to state a single match of this symbol before or after. This is done using a negative lookbehind ( \@<! In Vim regex syntax) and lookahead ( \@! ), Including the match itself ( a\{2} ):

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

simplification

These statements are difficult to introduce, if the border around the match is also a border without a keyword / keyword, you can use shorter \<\a\{2}\> statements (as in MosteM's answer), but this doesn’t work in the general case for example with xaax .

+8
source

You insert the line you are looking for, \< and \> , as in /\<aa\> , to exactly match that line.

+22
source

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

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

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

And branch extensions:

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

They cover all unforeseen situations - aa can be at the beginning, in the middle or at the end of any line. And there cannot be more than two a together.

  • \zs means the actual match begins.
  • \ze means the actual match ends here.
  • the first branch finds aa in a string 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 the line
  • and the fourth branch finds aa at the end of the line.

My mind is afraid of such fantastic things as looks at appearance, so I tried to stick to reasonably simple concepts of regular expressions.

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

+1
source

Move the cursor to the exact word you want to execute.

Press * (either Shitf + 8 or on the numeric keypad).

0
source

All Articles