refactor and fix pattern trimming