Optimized script and fixed error in regex replacement