解決方案使用正則表達式嘗試,
NSString *yourString = @"[email protected][email protected]";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"[A-Z0-9a-z._%+-][email protected][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 = @"[email protected][email protected]";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"[A-Z0-9a-z._%+-][email protected][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);
然後只
你不能做到這一點。您可能需要一個不能是值的一部分的分隔符,或者如果它出現在值中,則必須轉義分隔符。否則,無法知道如何正確拆分字符串。 – rmaddy 2013-05-01 04:56:14
我問了一個老大,他告訴我,我應該首先搜索字符串「@」字符。當我找到這個,然後我搜索一個「_」,並將其替換,如果它存在。作爲「@」後的第一個下劃線是分隔符。然後我應該從這個位置開始,然後重複上一步驟。直到字符串結束爲止。 – Jpk 2013-05-01 05:01:16
好的,但我不明白爲什麼這比它應該更難。如果將分隔符更改爲無法顯示在有效電子郵件地址中的字符,對於每個人來說,這會更有意義。 – rmaddy 2013-05-01 05:05:44