Today I Learned

hashrocket A Hashrocket project

Non-Greedy Vim Regex

Regex is by default greedy, meaning, if you used this regex /.*, on the following line:

a123,b123,c123,d123

You'd match everything up to the last comma a123,b123,c123. If you just want everything to the first comma you need to use a non-greedy matcher. In posix regex you could modify the * operator (match 0 or more) with the ? operator, like this: /.*?,/.

Vim however is a bit weird and doesn't support making the * operator non-greedy in this manner. You can however use curly braces to tell vim to match 0 or more, but as few as possible like this: /.\{-}, which will match just a123,.

Remember, the leading curly needs to be escaped with a slash \.

See :help pattern-overview for more!

See More #vim TILs
Every developer at Hashrocket is a Vim expert. Check out our development environment, Dotmatrix, and if you are in Chicago, come to the Vim Chicago Meetup hosted at our Chicago office.