Norbert
Norbert

Reputation: 765

Matching a string against multiple patterns

I have a question regarding the style of a solution for a pretty simple problem.

I have a program that matches a list of file names against a number of patterns. If the file name matches a pattern, the file is renamed and a counter is incremented.

Currently I'm matching against 4 different patterns like this

if ([file rangeOfString:pattern].location != NSNotFound) {
counter ++;
//rename file...
}

if ([file rangeOfString:pattern2].location != NSNotFound) {
counter2 ++;
//rename file...
}
[...]

The solution works well but does not scale. If I have to match against significantly more patterns.

So I thought about using something like

NSString *someRegexp = ...; 
NSPredicate *myTest = [NSPredicate predicateWithFormat:file, someRegexp]; 

if ([myTest evaluateWithObject: testString]){

}

However, I do not see any way to increment the counters in such a solution as they depend on the exact match....

So I was wondering whether anybody here knows a more comprehensive/nice solution for this problem.....

Thanks in advance Norbert

Upvotes: 0

Views: 61

Answers (1)

lead_the_zeppelin
lead_the_zeppelin

Reputation: 2052

How about subclassing NSString, adding a counter to track the match count.

@interface PatternMatchingString : NSString

@property (readwrite) NSUInteger matchCount;

@end

-(void)patternMatching
{
    for(PatternMatchingString *pattern in arrayOfPatterns)
    {
        if([file rangeOfString:pattern].location != NSNotFound)
            pattern.matchCount++;
    }
}

Upvotes: 1

Related Questions