refactored substring matching code