I’m working with NSRegularExpression to read a text and find out hashtag.
This is NSString that I used in regularExpressionWithPattern.
- (NSString *)hashtagRegex
{
return @"#((?:[A-Za-z0-9-_]*))";
//return @"#{1}([A-Za-z0-9-_]{2,})";
}
And this is my method:
// Handle Twitter Hashtags
detector = [NSRegularExpression regularExpressionWithPattern:[self hashtagRegex] options:0 error:&error];
links = [detector matchesInString:theText options:0 range:NSMakeRange(0, theText.length)];
current = [NSMutableArray arrayWithArray:links];
NSString *hashtagURL = @"http://twitter.com/search?q=%23";
//hashtagURL = [hashtagURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
for ( int i = 0; i < [links count]; i++ ) {
NSTextCheckingResult *cr = [current objectAtIndex:i];
NSString *url = [theText substringWithRange:cr.range];
NSString *nohashURL = [url stringByReplacingOccurrencesOfString:@"#" withString:@""];
nohashURL = [nohashURL stringByReplacingOccurrencesOfString:@" " withString:@""];
[theText replaceOccurrencesOfString:url
withString:[NSString stringWithFormat:@"<a href=\"%@%@\">%@</a>", hashtagURL, nohashURL, url]
options:NSLiteralSearch
range:NSMakeRange(0, theText.length)];
current = [NSMutableArray arrayWithArray:[detector matchesInString:theText options:0 range:NSMakeRange(0, theText.length)]];
}
[theText replaceOccurrencesOfString:@"\n" withString:@"<br />" options:NSLiteralSearch range:NSMakeRange(0, theText.length)];
[_aWebView loadHTMLString:[self embedHTMLWithFontName:[self fontName]
size:[self fontSize]
text:theText]
baseURL:nil];
Everything worked but it figured out a little issue when I use a string like this:
NSString * theText = @"#twitter #twitterapp #twittertag";
My code highlights only #twitter on each word and not the second part of it (#twitter #twitter(app) #twitter(tag)).
I hope someone will help me!
Thank you 🙂
The statement
is replacing all instances of the string
urlwith the replacement string. In the example you give, the first time through the loop,urlis@"#twitter", and all three occurrences of that string withintheTextare replaced in one go. This is whattheTextlooks like then:So, of course, the next two times round the loop, the results are not quite what you expect… !
I think the fix is to limit the range of the replacement: