Vim Tips: Replace 0px with 0

I like little wins. I was just looking through the CSS file for this site and noticed that - for some reason - I'd used 0px instead of 0 a LOT of times. Most values need numbers (10em, 10px, 10% and 10pt are all very difference sizes) however 0 is one of the few valeus which is the same in all cases (0px, 0pt, 0% and 0 are all zero!). This adds up to wasted data and bandwidth; admitedly not a lot, but still Every Little Helps!

So I fired up Vim. Initially, I just did:


%s=0px=0=g

This told Vim to do a global (%) search (s) using the = as a delimiter and find all instances of 0px and replace with 0. The g tells Vim not to stop once its found the first instance on the line. And it worked. In fact, it worked too well… Suddenly, all instances of 10px turned into 10. Bugger!

The solution ended up being a simple regular expression (God Save Regular Expressions):


%s=\([^0-9]\)0px=\10=g

I admit, it looks complicated, but essentially it's the same as the first search, however we've told it to match 0px preceded by a non numeric character (that's the [^0-9], the ^ means not and the 0-9 is a range). The reason it's in brackets is that we need to be able to reference that later on. In the replace we use \1 to tell Vim to look at the first group in the regex pattern (the bracketed non-numeric character). The unfortunately side effect of the non-numeric pattern preceding the 0px is that it also matched spaces and colons. The replace code which references this allows the matches non-numeric character to be placed back in front of the zero.