Use a sub-process(fork) with to BSD::Resource(even on Linux) to ulimit memory and kill the child after some timeout
Perhaps #2 is overkill, there may be a simpler method, like additional flags to #1. Suggest to add a maxiterations to limit the number of times re is allowed to loop and maxmem.