Refactor regex and some logic