我有一个来自服务器的字符串,想检查它是否包含电话号码、邮件地址和电子邮件等表达式。我得到了成功的情况下,电话号码和通讯地址,但没有电子邮件。为此,我使用了NSDataDetector。例如
NSString *string = sourceNode.label; //coming from server
//Phone number
NSDataDetector *phoneDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:nil];
NSArray *phoneMatches = [phoneDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in phoneMatches) {
if ([match resultType] == NSTextCheckingTypePhoneNumber) {
NSString *matchingStringPhone = [match description];
NSLog(@"found URL: %@", matchingStringPhone);
}
} 但是如何对电子邮件做同样的事情呢?
发布于 2012-01-13 23:00:18
在苹果文档中,识别的类型似乎不包括电子邮件:http://developer.apple.com/library/IOs/#documentation/AppKit/Reference/NSTextCheckingResult_Class/Reference/Reference.html#//apple_ref/c/tdef/NSTextCheckingType
所以我建议你使用Regexp。它将如下所示:
NSString* pattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]+";
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
if ([predicate evaluateWithObject:@"johndoe@example.com"] == YES) {
// Okay
} else {
// Not found
}编辑:
因为@dunforget得到了最好的解决方案,而我的解决方案是公认的,please read his answer。
发布于 2013-07-18 19:05:08
if (result.resultType == NSTextCheckingTypeLink)
{
if ([result.URL.scheme.locaseString isEqualToString:@"mailto"])
{
// email link
}
else
{
// url
}
}电子邮件地址属于NSTextCheckingTypeLink。只需在找到的URL中查找"mailto:“,您就会知道这是一封电子邮件或URL。
发布于 2012-08-30 19:12:16
尝试下面的代码,看看它是否适用于您:
NSString * mail = so@so.com
NSDataDetector * dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSTextCheckingResult * firstMatch = [dataDetector firstMatchInString:mail options:0 range:NSMakeRange(0, [mail length])];
BOOL result = [firstMatch.URL isKindOfClass:[NSURL class]] && [firstMatch.URL.scheme isEqualToString:@"mailto"];https://stackoverflow.com/questions/8850918
复制相似问题