How do you detect words that start with “@” or “#” within an NSString?

瘦欲@ 提交于 2019-11-28 09:22:07

You can use NSRegularExpression class with a pattern like #\w+ (\w stands for word characters).

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
for (NSTextCheckingResult *match in matches) {
    NSRange wordRange = [match rangeAtIndex:1];
    NSString* word = [string substringWithRange:wordRange];
    NSLog(@"Found tag %@", word);
}

You can break a string into pieces (words) by using componentsSeparatedByString: and then check the first character of each one.

Or, if you need to do it while the user is typing, you can provide a delegate for the text view and implement textView:shouldChangeTextInRange:replacementText: to see typed characters.

Made a category of NSString for that. It's very simple: Find all words, return all words that start with # to get the hashtags.

Relevant code segment below - rename those methods & the category too...

@implementation NSString (PA)
// all words in a string
-(NSArray *)pa_words {
    return [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

// only the hashtags
-(NSArray *)pa_hashTags {
    NSArray *words = [self pa_words];
    NSMutableArray *result = [NSMutableArray array];
    for(NSString *word in words) {
        if ([word hasPrefix:@"#"])
            [result addObject:word];
    }
    return result;
}
Tiziano
if([[test substringToIndex:1] isEqualToString:@"@"] ||
   [[test substringToIndex:1] isEqualToString:@"#"])
{
    bla blah blah
}

Here's how you can do it using NSPredicate

You can try something like this in the UITextView delegate:

- (void)textViewDidChange:(UITextView *)textView
{
    _words = [self.textView.text componentsSeparatedByString:@" "];
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[cd] '@'"];
    NSArray* names = [_words filteredArrayUsingPredicate:predicate];
    if (_oldArray)
    {
        NSMutableSet* set1 = [NSMutableSet setWithArray:names];
        NSMutableSet* set2 = [NSMutableSet setWithArray:_oldArray];
        [set1 minusSet:set2];
        if (set1.count > 0)
            NSLog(@"Results %@", set1);
    }
    _oldArray = [[NSArray alloc] initWithArray:names];
}

where _words, _searchResults and _oldArray are NSArrays.

Use following expression to detect @ or # in string

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(#(\\w+)|@(\\w+)) " options:NSRegularExpressionCaseInsensitive error:&error];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!