Minimize Greed

3.7
(287)

The default behavior in Vim is to be greedy when matching patterns. Greedy patterns select the largest string of characters that match the pattern. Often this is not what you want. Let’s suppose you’d like to match one portion of a series of lines containing quoted text:

{
  "name": "Andy",
  "last": "Dufresnes",
  "id": 37927
}

To match “name”, I’d first attempt to use the pattern /”.*”. The * is the regex that corresponds to any character. Watch what happens:

Notice now the pattern matches the entire line? This is because .* is greedy. If we wish to match the minimum length match possible, .\{-} will match the fewest characters possible to make a match.

In your patterns, instead of * use \{-} and you’ll get the desired match. Here you can the non-greedy pattern match:

For more details, see the help docs in Vim with the :help non-greedy command.

How useful was this post?

Average rating 3.7 / 5. Vote count: 287

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Andy Libby

27 Posts

Rider of bicycles. Writer of code. User of Vim.
View all posts

Leave a reply

Your email address will not be published. Required fields are marked *