我该如何分开这样的字符串?

时间:2013-05-01 04:54:08

标签: ios objective-c nsstring tokenize

我得到一个NSString包含连接在一起的不同电子邮件,如

  

def_ghi @ hotmail.com_abc_1 @ me.com

每封电子邮件由下划线分隔。问题是,如果我尝试使用下划线字符分隔字符串,它还会细分单个电子邮件地址,因为下划线字符也可以在单个电子邮件中。我试过的东西给了我这个结果

  

DEF

     

ghi@hotmail.com

     

ABC

     

1@me.com

这是我的代码

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

请帮帮我。

修改  我问了一个大四学生,他告诉我,我应该首先在字符串中搜索“@”字符。当我找到它时,然后我搜索一个“_”并替换它,如果它存在。作为“@”之后的第一个下划线是我应该从这个位置开始然后再重复上一步。我这样做直到字符串结束。请有人帮我这个。

4 个答案:

答案 0 :(得分:3)

使用正则表达式的解决方案,

NSString *yourString = @"def_ghi@hotmail.com_abc_1@me.com";
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);

}];

编辑:如何收集它们,

声明一个这样的变量,

@property(nonatomic, strong) NSMutableArray *emailsArray;



 _emailsArray = [[NSMutableArray alloc] init];

NSString *yourString = @"def_ghi@hotmail.com_abc_1@me.com";
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);

答案 1 :(得分:1)

这里有很多很好的答案,关于如何从你自己发现的那个有点凌乱的字符串重新构建邮件地址的原始列表。

我会提出一个基于NSScanner的解决方案,它看起来很合适:

NSString *messyString = @"def_ghi@hotmail.com_abc_1@me.com";

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;
}

答案 2 :(得分:0)

尝试

NSString *string = @"def_ghi@hotmail.com_abc_1@me.com";
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);

答案 3 :(得分:0)

根据您的要求,这样的事情对您有用:

NSString *string = @"def_ghi@hotmail.com_abc_1@me.com";
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);