Thanks Bloodnok, that's exactly what I was looking for.
I want to avoid using a package to solve this problem because I have to do the same thing in some PHP code. I don't know of a PHP module that can do what I need, preg_replace will work using Perl regular expressions.
This is one of those things I've been wanting to solve for awhile but kept putting it off.