DEV Community

Colin Bartlett
Colin Bartlett

Posted on • Originally published at vimtricks.substack.com

VimTrick: Non-greedy pattern matching

Good morning Vim users of Dev.to! Another Monday has arrived and that means another in my series of Vim tricks and tips...

You might already know that pattern matching in Vim is greedy by default. That means, it will select the largest string that matches your pattern. For example, suppose you have:

{
  "name": "Andy",
  "last": "Dufresnes",
  "id": 37927
}
Enter fullscreen mode Exit fullscreen mode

If you pattern match with /”.*”, Vim will select the entire string on that line: "name": "Andy". But what if what we really want is just the first "name"?

Instead of .* use .\{-} and Vim will select just the smallest string that matches the pattern instead of the largest.

I have screenshots and more details over on my post on VimTricks.

Let me know if you find this helpful! I still have not internalized it for every day use but I've found it very helpful when I do recall it!

Top comments (0)