Consider modifying the KMP matching algorithm.