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

假如想象 提交于 2019-11-27 02:57:29

问题


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!


回答1:


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);
}



回答2:


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.




回答3:


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;
}



回答4:


if([[test substringToIndex:1] isEqualToString:@"@"] ||
   [[test substringToIndex:1] isEqualToString:@"#"])
{
    bla blah blah
}



回答5:


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.




回答6:


Use following expression to detect @ or # in string

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(#(\\w+)|@(\\w+)) " options:NSRegularExpressionCaseInsensitive error:&error];


来源:https://stackoverflow.com/questions/10353567/how-do-you-detect-words-that-start-with-or-within-an-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!