Search pattern in string using regex in obj-c

Posted by manileo86 on Stack Overflow See other posts from Stack Overflow or by manileo86
Published on 2012-04-03T11:01:40Z Indexed on 2012/04/03 11:28 UTC
Read the original article Hit count: 218

I'm working on a string pattern match algorithm. I use NSRegularExpression for finding the matches. For ex: I've to find all words starting with '#' in a string.. Currently I use 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 use it as below:

NSRegularExpression *regexp = SearchTagRegularExpression();
[regexp enumerateMatchesInString:searchString 
                         options:0 range:stringRange 
                      usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{       
  // comes here for every match with range
}];

This works properly. But i just want to know if this is the best way. suggest if there's any better alternative...

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c