move regex compilation out, and simplify code