How do you detect words starting with "@" or "#" in NSString?

I am creating a Twitter iPhone application and it needs to determine when you enter the hashtag or @ -mention inside the string in a UITextView.

How do I find all the words preceding the characters "@" or "#" in NSString?

Thank you for your help!

+8
ios objective-c nsstring twitter uitextview
source share
6 answers

You can use the NSRegularExpression class with a pattern such as # \ 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); } 
+22
source share

You can break a string into chunks (words) using SeparatedByString: components and then check the first character of each of them.

Or, if you need to do this while the user is typing, you can provide a delegate for the text view and implement textView: shouldChangeTextInRange: replacementText: see the entered characters.

+2
source share

For this, the NSString category was created. It is very simple: find all words, return all words starting with C # to get hashtags.

Relevant code segment below - rename these methods and 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; } 
+1
source share
 if([[test substringToIndex:1] isEqualToString:@"@"] || [[test substringToIndex:1] isEqualToString:@"#"]) { bla blah blah } 
0
source share

Here's how you can do it using NSPredicate

You can try something similar in doing a UITextView:

 - (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
source share

Use the following expression to detect @ or # in a string

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

All Articles