使用正则表达式的解决方案,
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);