Fixing substitution to work with patterns.

@dwightguth please review.