8

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
  • do you need to get those characters during editing or after editing(maybe by calling an action)? according to this point i may help you
    – ilhnctn
    Apr 27, 2012 at 15:39

6 Answers 6

22

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);
}
6
  • This is wrong. Twitter recently updated the hashtag filters, and now supports only certain non-latin characters. For example, you won't match Arabic hashtags. Apr 27, 2012 at 15:51
  • That should be \\w+ and not just \w+.
    – sch
    Apr 27, 2012 at 16:09
  • what is the significance of + ?
    – devdoe
    Jun 7, 2013 at 4:56
  • 2
    More adequate pattern for Twitter hashtags would be @"(^|\\W)(#|\\uFF03)(\\w*\\p{L}\\w*)". It does not match things like "one#two" and "We're #1" and works fine for non-ASCII letters. Sep 27, 2013 at 12:03
  • @VadimYelagin Can you share how you used the twitter-text-java regex on Objective-C/iOS?
    – SleepNot
    Nov 7, 2014 at 9:25
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.

2
  • 1
    Defining word boundaries is always going to be application-specific. componentsSeparatedByString: is a decent technique but the programmer still has to make decisions about "either/or" and "A1" and "neo-conservative" and a bunch of other constructions. Apr 27, 2012 at 16:14
  • Implemented this similarly below. You've got a point about word boundaries though. One could conceivably have hashtags like I #like/#love this. Hm....
    – n13
    Mar 30, 2014 at 15:57
1

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;
}
0
if([[test substringToIndex:1] isEqualToString:@"@"] ||
   [[test substringToIndex:1] isEqualToString:@"#"])
{
    bla blah blah
}
1
  • Don't forget to check that the text is longer than 1 before doing substring operations. Otherwise some user will enter an empty message and be mad when the app crashes. May 1, 2012 at 10:35
0

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.

0

Use following expression to detect @ or # in string

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.