如何使用NSRegularExpression从字符串中提取电子邮件地址

时间:2012-11-08 12:28:12

标签: iphone ios regex

我正在制作iphone应用程序。我有一个场景,我有一个巨大的字符串,有很多数据,我想从字符串中只提取电子邮件地址。

例如,如果字符串是

  

asdjasjkdh asdhajksdh jkashd sample@email.com asdha jksdh asjdhjak sdkajs test@gmail.com

我应该提取“sample@email.com”和“test@gmail.com”

我还想从字符串中提取日期

例如,如果字符串是

  

asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd sample@email.com asdha jksdh asjdhjak sdkajs test@gmail.com

我应该提取“01/01/2012”和“12/11/2012”

一个小代码snipet,将非常有帮助。

提前致谢

3 个答案:

答案 0 :(得分:10)

这将做你想要的:

// 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设置为您要搜索的字符串即可。您可能希望使用提取的字符串matchText执行某些操作,而不是NSLog()方法。您可以随意使用不同的正则表达式字符串来提取电子邮件,只需替换代码中regexString的值即可。

答案 1 :(得分:1)

NSArray *chunks = [mylongstring componentsSeparatedByString: @" "];

for(int i=0;i<[chunks count];i++){
    NSRange aRange = [chunks[i] rangeOfString:@"@"];
    if (aRange.location !=NSNotFound) NSLog(@"email %@",chunks[i] );
}

答案 2 :(得分:0)

您可以使用此正则表达式来匹配电子邮件

 [^\s]*@[^\s]*

和此正则表达式匹配日期

 \d+/\d+/\d+