sankoz
sankoz

Reputation: 552

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

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\)\@!$

Upvotes: 8

Views: 4390

Answers (2)

None
None

Reputation: 2598

/\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

Upvotes: 2

Andrew Cheong
Andrew Cheong

Reputation: 30273

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

Twinkle\(.*Twinkle\)\@!.*$
       ^          ^    ^^

Upvotes: 6

Related Questions