String search pattern using regex in obj-c
I am working on a string matching algorithm. I am using NSRegularExpression to find matches. For example: I have to find all words starting with "#" in the string. I am currently using the following regex function:
static NSRegularExpression *_searchTagRegularExpression;
static inline NSRegularExpression * SearchTagRegularExpression()
{
if (!_searchTagRegularExpression)
{
_searchTagRegularExpression = [[NSRegularExpression alloc]
initWithPattern:@"(?<!\\w)#([\\w\\._-]+)?"
options:NSRegularExpressionCaseInsensitive
error:nil];
}
return _searchTagRegularExpression;
}
and I am using it like below:
NSString *searchString = @"Hi, #Hash1 #Hash2 #Hash3...";
NSRange searchStringRange = NSMakeRange(0, searchString.length);
NSRegularExpression *regexp = SearchTagRegularExpression();
[regexp enumerateMatchesInString:searchString
options:0
range:searchStringRange
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{
// comes here for every match with range ( in this case thrice )
}];
This works correctly. But I just want to know if this is the best way. suggest if there is a better alternative ...
source to share
Actually your suggested model and implementation is pretty good:
-
The pattern is pretty accurate with its use of (fancy) negative appearance with zero width behind the statement to make sure you only match at the beginning of a word. It works correctly at the beginning of a line eg.
-
The implementation reuses the regex object and avoids recompiling the template.
If you want me to be nitpicking: you can drop the option NSRegularExpressionCaseInsensitive
as your template doesn't use any parts that have case.
source to share