这将做你想要的:
// regex string for emails (feel free to use a different one if you prefer)
NSString *regexString = @"([A-Za-z0-9_\\-\\.\\+])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]+)";
// experimental search string containing emails
NSString *searchString = @"asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd sample@email.com asdha jksdh asjdhjak sdkajs test@gmail.com";
// track regex error
NSError *error = NULL;
// create regular expression
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:0 error:&error];
// make sure there is no error
if (!error) {
// get all matches for regex
NSArray *matches = [regex matchesInString:searchString options:0 range:NSMakeRange(0, searchString.length)];
// loop through regex matches
for (NSTextCheckingResult *match in matches) {
// get the current text
NSString *matchText = [searchString substringWithRange:match.range];
NSLog(@"Extracted: %@", matchText);
}
}
使用上面的示例字符串:
asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd sample@email.com asdha jksdh asjdhjak sdkajs test@gmail.com
输出是:
Extracted: sample@email.com
Extracted: test@gmail.com
要使用代码,只需设置searchString
为您要搜索的字符串。代替 NSLog() 方法,您可能想要对提取的字符串做一些事情matchText
。随意使用不同的正则表达式字符串来提取电子邮件,只需替换regexString
代码中的值。