Jpk
Jpk

Reputation: 21

How do I separate strings like this?

I get an NSString containing different emails concatenated together like

[email protected][email protected]

Each email is separated by an underscore.The problem is if I try to separate the string using the underscore character it would also subdivide a single e-mail address as an underscore character can also come in within a single e-mail. What I've tried gives me this result

def

[email protected]

abc

[email protected]

Here is my code

NSString *string = //The string I am receiving.
NSArray *chunks = [string componentsSeparatedByString: @"_"];

Please help me.

EDIT: I asked a senior and he told me that I should first search the string for "@" character.When I find this,then I search for an "_" and replace it if it exists.As the first underscore after "@" is the separator.I should then start from this location and again repeat the previous step.I do this till the string ends.Please somebody help me with this.

Upvotes: 0

Views: 335

Answers (4)

Monolo
Monolo

Reputation: 18253

There are many good answers here on how to re-construct the original list of mail addresses from that somewhat messy string you found yourself with.

I would propose an NSScanner based solution, it seems to be well suited:

NSString *messyString = @"[email protected][email protected]";

NSScanner *mailScanner = [NSScanner scannerWithString:messyString];

NSMutableArray *mailAddresses = [NSMutableArray array];

while (YES) {

    NSString *recipientName;
    NSString *serverName;
    BOOL found = [mailScanner scanUpToString:@"@" intoString:&recipientName];
    found |= [mailScanner scanUpToString:@"_" intoString:&serverName];
    if ( !found ) break;

    [mailAddresses addObject:[recipientName stringByAppendingString:serverName]];

    // Consume the delimiting underscore
    found = [mailScanner scanString:@"_" intoString:nil];
    if ( !found ) break;
}

Upvotes: 1

Thilina Chamath Hewagama
Thilina Chamath Hewagama

Reputation: 9040

Solution using regular expressions,

NSString *yourString = @"[email protected][email protected]";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
                              options:NSRegularExpressionCaseInsensitive
                              error:&error];
[regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){

    // detect email addresses
    NSString *email = [yourString substringWithRange:match.range];

    //this part remove the '_' between email addresses
    if(match.range.location != 0){
        if([email characterAtIndex:0]=='_'){
            email = [email substringFromIndex:1];
        }
    }

    //print the email address
    NSLog(@"%@",email);

}];

EDIT: how to collect them,

declare a variable like this,

@property(nonatomic, strong) NSMutableArray *emailsArray;



 _emailsArray = [[NSMutableArray alloc] init];

NSString *yourString = @"[email protected][email protected]";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
                              options:NSRegularExpressionCaseInsensitive
                              error:&error];
[regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){

    // detect email addresses
    NSString *email = [yourString substringWithRange:match.range];

    //this part remove the '_' between email addresses
    if(match.range.location != 0){
        if([email characterAtIndex:0]=='_'){
            email = [email substringFromIndex:1];
        }
    }

    //print the email address
    NSLog(@"%@",email);
    [self.emailsArray addObject:email];
}];


NSLog(@"%@",self.emailsArray);

Upvotes: 3

rmaddy
rmaddy

Reputation: 318824

Given your requirements then something like this should work for you:

NSString *string = @"[email protected][email protected]";
NSMutableArray *addresses = [NSMutableArray array];
NSUInteger currentIndex = 0; // start from beginning
// Stop when we are past the end of the string
while (currentIndex < string.length) {
    // Find the next @ symbol
    NSRange atRange = [string rangeOfString:@"@" options:0 range:NSMakeRange(currentIndex, string.length - currentIndex)];
    if (atRange.location != NSNotFound) {
        // We found another @, not look for the first underscore after the @
        NSRange underRange = [string rangeOfString:@"_" options:0 range:NSMakeRange(atRange.location, string.length - atRange.location)];
        if (underRange.location != NSNotFound) {
            // We found an underscore after the @, extract the email address
            NSString *address = [string substringWithRange:NSMakeRange(currentIndex, underRange.location - currentIndex)];
            [addresses addObject:address];
            currentIndex = underRange.location + 1;
        } else {
            // No underscore so this must be the last address in the string
            NSString *address = [string substringFromIndex:currentIndex];
            [addresses addObject:address];
            currentIndex = string.length;
        }
    } else {
        // no more @ symbols
        currentIndex = string.length;
    }
}

NSLog(@"Addresses: %@", addresses);

Upvotes: 0

Anupdas
Anupdas

Reputation: 10201

Try

NSString *string = @"[email protected][email protected]";
NSArray *stringComponents = [string componentsSeparatedByString:@"_"];

NSMutableString *mutableString = [NSMutableString string];
NSMutableArray *emailIDs = [NSMutableArray array];
for (NSString *component in stringComponents) {
    if (!mutableString) {
        mutableString = [NSMutableString string];
    }
    [mutableString appendFormat:@"_%@",component];

    if ([component rangeOfString:@"@"].location != NSNotFound) {
        [emailIDs addObject:[mutableString substringFromIndex:1]];
        mutableString = nil;
    }
}

NSLog(@"%@",emailIDs);

Upvotes: 0

Related Questions