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

问题描述:

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

例如,如果字符串是像

asdjasjkdh asdhajksdh jkashd [email protected] asdha jksdh asjdhjak sdkajs [email protected]

我应该提取物 “[email protected]”和“[email protected]

,我也想只提取日期,从字符串

例如,如果字符串是像

asdjasjkdh 01/01/2012 asdhajksdh jkas 2012年12月11日高清[email protected] asdha jksdh asjdhjak sdkajs [email protected]

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

一小段snipet,会很有帮助。

在此先感谢

这会做你想要什么:

// 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 [email protected] asdha jksdh asjdhjak sdkajs [email protected]"; 

// 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 2012年12月11日高清[email protected] asdha jksdh asjdhjak sdkajs [email protected]

的输出是:

Extracted: [email protected] 
Extracted: [email protected] 

要使用的代码,只需设置searchString您要搜索的字符串。除了NSLog()方法外,您可能还想对提取的字符串matchText执行一些操作。随意使用不同的正则表达式字符串来提取电子邮件,只需在代码中替换regexString的值即可。

+0

不用说,使用日期正则表达式,如果你想提取日期! – Anton

您可以使用此正则表达式匹配的邮件

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

,这正则表达式匹配日期

\d+/\d+/\d+ 
+0

似乎没有工作,你能提供简单的代码片段。 –

+0

@syedimty我dnt了解'ios',但是你应该使用类似'match'的方法,如果它存在..不确定关于那个 – Anirudha

+0

感谢您的回复,请尝试并让您知道 –

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]); 
} 
+0

此代码将文本按空格分隔,循环遍历每个块都在寻找'@'符号。我会建议使用正则表达式来识别电子邮件,因为它会更准确。 – Anton

+0

相反,这是避免**正则表达式的好方法,当它不是必需的时候,可能会使事情变得不必要地复杂化。 – pasawaya

+0

是的,但我不同意这里没有必要。除了格式不正确的电子邮件地址外,还可能在文本中遇到其他使用'@'的情况(例如对网站句柄的引用,像Apple @ 2x等图像文件名称)。正则表达式执行准确的验证和查找:) – Anton