Skip to content

Instantly share code, notes, and snippets.

@dafi
Created May 5, 2012 08:46
Show Gist options
  • Save dafi/2601026 to your computer and use it in GitHub Desktop.
Save dafi/2601026 to your computer and use it in GitHub Desktop.
Convert a glob string to a valid regular expression string
#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
#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment