This code will run A LOT faster if you use precompiled regexp via re.compile() and pass it as an argument or just do it out of the cycle. Right now, it compiles on every iteration and slows the whole thing down.