dafi
5/5/2012 - 8:46 AM

Convert a glob string to a valid regular expression string

Convert a glob string to a valid regular expression string

#import "RegExpUtils.h"

@implementation RegExpUtils

+ (NSString*)convertGlobMetaCharsToRegexpMetaChars:(NSString*)glob {
#define VD_MK_GLOB(index, r, t, regexString, templateString) \
    r[index] = [[NSRegularExpression alloc] initWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:nil];\
    t[index] = templateString;
#define VD_REPLACE_REGEXP(index, r, t, str) [r[index] stringByReplacingMatchesInString:str options:0 range:NSMakeRange(0, str.length) withTemplate:t[index]];
    
    static dispatch_once_t pred;
    static NSRegularExpression* regex[3];
    static NSString* templates[3];

    dispatch_once(&pred, ^{
        VD_MK_GLOB(0, regex, templates, @"([.^$+(){}\\[\\]\\\\|])", @"$1");
        VD_MK_GLOB(1, regex, templates, @"\\?", @"(.|[\r\n])");
        VD_MK_GLOB(2, regex, templates, @"\\*", @"(.|[\r\n])*");
    });

    NSString* re = glob;
    re = VD_REPLACE_REGEXP(0, regex, templates, re);
    re = VD_REPLACE_REGEXP(1, regex, templates, re);
    re = VD_REPLACE_REGEXP(2, regex, templates, re);

    return re;
};

@end
#import <Foundation/Foundation.h>

@interface RegExpUtils

/**
 * Convert a glob string to a valid regular expression string
 * strings like "*m" are converted to ".*m"
 * Available on OSX 10.7 or above
*/
+ (NSString*)convertGlobMetaCharsToRegexpMetaChars:(NSString*)glob;

@end