Q:

parsing string starting with @ and # in objective-C

So I am trying to parse a string that has the following format:
baz@marroon#red#blue #big@cat#dog
or, it can also be separated by spaces:
baz @marroon #red #blue #big @cat #dog
and here's how I am doing it now:
- (void) parseTagsInComment:(NSString *) comment
{
    if ([comment length] > 0){
        NSArray * stringArray = [comment componentsSeparatedByString:@" "];
        for (NSString * word in stringArray){
            
        }
    }
}

I've got the components separated by space working, but what if it has no space.. how do I iterate through these words? I was thinking of using regex.. but I have no idea on how to write such regex in objective-C. Any idea, for a regex that would cover both of these cases?
Here's my first attempt:
NSError * error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(@|#)\\S+" options:NSRegularExpressionCaseInsensitive error:&error];
    
    NSArray* wordArray = [regex matchesInString:comment 
                                      options:0 range:NSMakeRange(0, [comment length])];
    
    for (NSString * word in wordArray){
       
    }

Which doesn't work.. I think my regex is wrong.

A:

Here is a way to do it using NSScanner that puts the separated strings and a string representation of their ranges into an array (this assumes that your original string started with a # -- if it doesn't and you need it to, then just prepend the hash to the string at the start).
NSMutableArray *array = [NSMutableArray array];
    NSString *str = @"#baz@marroon#red#blue #big@cat#dog";
    NSScanner *scanner = [NSScanner scannerWithString:str];
    NSCharacterSet *searchSet = [NSCharacterSet characterSetWithCharactersInString:@"#@"];
    NSString *outputString;

    while (![scanner isAtEnd]) {
        [scanner scanUpToCharactersFromSet:searchSet intoString:nil];
        [scanner scanCharactersFromSet:searchSet intoString:&outputString];
        NSString *symbol = [outputString copy];
        [scanner scanUpToCharactersFromSet:searchSet intoString:&outputString];
        NSString *wholePiece = [[symbol stringByAppendingString:outputString]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *rangeString = NSStringFromRange([str rangeOfString:wholePiece]);
        [array addObject:wholePiece];
        [array addObject:rangeString];
    }
    NSLog(@"%@",array);

