solution to pattern substitution