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 ...

+3


source to share


2 answers


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.

+1


source


What you are doing is a good way. You can also do this,



for(NSString *match in [string componentSeperatedByString:@" "])
    {
      if([match hasPrefix:@"#"])
       {
         //do what you like.
        }
     }

      

-1


source







All Articles