Skip to content
AliSoftware edited this page Mar 19, 2015 · 5 revisions

How to detect Hashtags and Mentions in a string

The magic Regular Expression

The easiest way to do that is using an NSRegularExpression. The trick is to use the right RegExp for that.

  • For Hashtags (#hashtag), the regular expression to use is \B#\w+
  • For Twitter mentions (@mention), the regular expression is pretty similar: \B@\w+

Note: Remember to double-escape backslashes when using strings as a quoted literals in your source code, so one should actually use @"\\B#\\w+" in your source code for the NSString literal.

The rest is pretty straightforward as you can use the RegExp to enumerate all matches in a given string and do whatever you want with each match (like changing its font color, adding a link to that range of text, etc.)

Complete example:

NSMutableAttributedString* attrStr = …;

NSString* pattern = @"\\B#\\w+";
NSRegularExpression* hashTagRegExp = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
NSString* str = attrStr.string; // The plain text we will iterate over

[hashTagRegExp enumerateMatchesInString:str options:0 range:NSMakeRange(0,str.length)
                             usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop)
{
    // For each "#xxx" hashtag found, add a custom link:
    NSString* tag = [[str substringWithRange:match.range] substringFromIndex:1]; // get the tag without the "#"
    NSString* linkURLString = [NSString stringWithFormat:@"tag:%@", tag]; // build a "tag:xxx" link
    [attrStr setURL:[NSURL URLWithString:linkURLString] range:match.range]; // add the URL
    [attrStr setTextColor:[UIColor blueColor] range:match.range]; // also, color it blue
}];

// Once there, 'attrStr' will have its hashtags colored in blue and a "tag:xxx" URLs associated with them
// so you can use that later to detect which tag has been tapped using `-[NSURL host]` to extract that `xxx` part
// from the custom-built URL.