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

前端 未结 6 1676
时光取名叫无心
时光取名叫无心 2020-12-09 21:49

I\'m building a Twitter iPhone app, and it needs to detect when you enter a hashtag or @-mention within a string in a UITextView.

How do I find all words preceded by

6条回答
  •  爱一瞬间的悲伤
    2020-12-09 22:26

    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.

提交回复
热议问题