Might be just me, but this sounds like a call for a regex expert.
I'd love to be able to write up something for you, but I'm still learning regex.