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.
Was this useful? Help us improve!
With your feedback, we can improve VimTricks. Click a link to vote: