Refactored the match logic and cache the regex patterns.