Non-greedy regex in Vim

3.7
(556)

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:

Greedy regex in Vim with .*

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:

Greedy regex in Vim with .\{-}

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

Here’s a short video of both greedy regex and non-greedy regex in action:

How useful was this tip?

Average rating 3.7 / 5. Vote count: 556

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

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

36 Posts

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