How do you detect words that start with “@” or “#”

2019-01-18 06:12发布

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 the "@" or "#" characters within an NSString?

Thanks for your help!

6条回答
Ridiculous、
2楼-- · 2019-01-18 06:23

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-18 06:33

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.

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-18 06:37

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);
}
查看更多
霸刀☆藐视天下
5楼-- · 2019-01-18 06:37

Use following expression to detect @ or # in string

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(#(\\w+)|@(\\w+)) " options:NSRegularExpressionCaseInsensitive error:&error];
查看更多
劳资没心,怎么记你
6楼-- · 2019-01-18 06:39

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;
}
查看更多
一夜七次
7楼-- · 2019-01-18 06:42
if([[test substringToIndex:1] isEqualToString:@"@"] ||
   [[test substringToIndex:1] isEqualToString:@"#"])
{
    bla blah blah
}
查看更多
登录 后发表回答