Refactor expect match loop into a helper function.