I find this logic really difficult to follow. Can this be made clearer? I'd much prefer a regex based solution.