Refactor code and move regex out of function