Non greedy matching in vim

If you want to match something in a line in vim, and have had problems.

Something like

aaabccbaaaabccbaaabccbaaaa

and you want to extract the first bccb from the string and replace the line with only the match. (say getting the link portion of weblinks from some source html)

you would be forgiven for doing

:s/.*b(.*)b.*/1/

Thats what I did and to my suprise it provided me with the equivalent of ccbaaaabccbaaabcc

The reason for this is that the b at the end of the match matches the last b in the string, and the .* is greedy and matches as many characters as it can.

The answer is to use the magic \{-} match, this does the same as * but means do it with a least matching algorithm.

:s/.*b(.{-})b.*/1/

does exactly what I expected, returning cc for this line.

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word