I think using $regsubex would be better in this case. Here is an updated version of the code:
Same syntax and all, just uses $regsubex.