Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go to the last match of a Vim search pattern

Tags:

regex

vim

In a line, how can Vim match only the last occurrence of a search pattern? Sort of like non-greedy, but from beginning.

e.g. In the following line, I want to match Twinkle little star (highlighted in bold):

Twinkle blah Twinkle blah blah Twinkle little star.

I tried negative lookahead like the following, but it is matching the full line:

Twinkle.*\(Twinkle\)\@!$
like image 647
sankoz Avatar asked Nov 09 '12 05:11

sankoz


People also ask

How do I go to previous search in vi?

vi positions the cursor at the next occurrence of the string. For example, to find the string “meta,” type /meta followed by Return. Type n to go to the next occurrence of the string. Type N to go to the previous occurrence.

What does F do in vim?

If you press "F", Vim will move the cursor backwards instead of forward. Given the previous sentence, if pressed "Fq", and the cursor was at the end of the line, it would move to the "q" in "quick".


2 Answers

Escape your parentheses and add a wildcard match before the anchor:

Twinkle\(.*Twinkle\)\@!.*$
       ^          ^    ^^
like image 90
slackwing Avatar answered Sep 24 '22 11:09

slackwing


/\v.*\zsTwinkle.*
  • ".*" greedily matches everything, backtracking on failure to match less (and potentially nothing)
  • "\zs" sets "start of match", useful for substitutions and cursor placement
  • the rest is what you want to match

Use ":set incsearch", load up some text into a buffer, and start typing the pattern to see how it's applied.

For example, a buffer:

Twinkle brightly little star
Twinkle brightly, Twinkle brightly little star

And substitution:

:%s/\v.*\zsTwinkle /&extra /

Gives:

Twinkle extra brightly little star
Twinkle brightly, Twinkle extra brightly little star
like image 27
Roger Pate Avatar answered Sep 21 '22 11:09

Roger Pate