I have a string, and I want to search words (tags) that begin with “#” and end with “.” or “,” or ” ” I found this online, but is limited because:
– You can find a single word in the string (although there are more words)
– “RangeOfString” does not allow multiple choices
NSString *stringText = @"test #hello #world";
NSString *result = nil;
// Determine "#"
NSRange hashRange = [stringText rangeOfString:@"#" options:NSCaseInsensitiveSearch];
if (hashRange.location != NSNotFound)
{
// Determine " " location according to "#" location
NSRange endHashRange;
endHashRange.location = hashRange.length + hashRange.location;
endHashRange.length = [stringText length] - endHashRange.location;
endHashRange = [stringText rangeOfString:@" " options:NSCaseInsensitiveSearch range:endHashRange];
if (endHashRange.location != NSNotFound)
{
// Tags found: retrieve string between them
hashRange.location += hashRange.length;
hashRange.length = endHashRange.location - hashRange.location;
result = [stringText substringWithRange:hashRange];
}
}
you have idea how can I do?
Thank you!
You can use
NSRegularExpressionclass, like this:You may need to play with your regular expression to get it just right. The reference that I liked describes the grammar of the regex language supported by Apple’s classes.