Improved regex logic