Ravenous Regex
Sunday, July 30th, 2006I like ViM. No… I love ViM. No… my fingers love ViM, and my brain doesn’t know it.
One thing I really like about ViM, is that after 10 years, I still learn new things. For example, today I learned how to construct non-greedy regex.
For one of my consulting gigs, I’m migrating a decent sized website into the rails framework. In doing so, I’m also converting (to the best of my ability and time) the site to use as much CSS as possible. Thus, gone are things like <font…> tags. The problem is trying to glob out the attributes of the font tag. How do you match <font size=”12px” color=”#ebeb1d”>? One might try “%s/<font.*>//g“. The problem with the ViM regex, is that the final > doesn’t get matched… rather, the regex is greedy, skips the intended > and magically find a > further on down the path. So how do you disable the “greediness” ?
The trick is to prefix the intended > with “.\{-0,\}”. (that’s a zero)
Here’s the actual ViM example that will match <font…..>:
:%s/<font.\{-0,\}>//g
I agree that the keystrokes are a bit insane but (a) it works and (b) it works. enjoy!





