Wulf's Webden

The Webden on WordPress

Non-greedy Expressions

| 0 comments

This is another of my notes-to-self about the Vim editor. I love the way it offers the power of regular expressions for searching and replacing strings of text but the default mode is “greedy”. This means that it finds the longest matching result it can on each line. For example, if I had a line from a song like “[C]Three [G]blind [C]mice” and I wanted to remove the chords, I couldn’t search for \[.*] – that looks like some kind of weird emoticon but would be read as anything between an opening and closing square bracket. Plug that in and the result would be “mice”.

Instead, you need a non-greedy regular expression. It is easily done but it seems to come up just infrequently enough that I have to check the documentation every time. However, it feels like I am just on the cusp of committing it to memory, hence this post to drive it home. If I used the search \[.\{-}] I would get the intended result of “Three blind mice”. The trick is to remember that the single asterisk character has to be replaced by {-} and an additional \ in front so that the system doesn’t try to do anything clever with the opening curly brace.

In other words – and perhaps this will help my memory – the non-greedy expression makes up for it by being greedy about the number of characters it requires!

Leave a Reply

Required fields are marked *.


This site uses Akismet to reduce spam. Learn how your comment data is processed.