Add regex support.

This also reorganizes and moves some cleanup code.