我有一个来自服务器的字符串,想检查它是否包含电话号码,邮件地址和电子邮件等表达式。我在电话号码和邮件地址方面取得了成功,但没有收到电子邮件。我为此目的使用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);
}
}
但如何为电子邮件做同样的事情?
答案 0 :(得分:27)
if(result.resultType == NSTextCheckingTypeLink)
{
if([result.URL.absoluteString rangeOfString:@"mailto:"].location != NSNotFound)
{
// email link
}
else
{
// url
}
}
电子邮件地址属于NSTextCheckingTypeLink。只需在找到的网址中查找“mailto:”,您就会知道它是一封电子邮件或网址。
答案 1 :(得分:8)
尝试以下代码,看看它是否适合您:
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"];
答案 2 :(得分:4)
在Apple文档中,似乎已识别的类型不包含电子邮件: http://developer.apple.com/library/IOs/#documentation/AppKit/Reference/NSTextCheckingResult_Class/Reference/Reference.html#//apple_ref/c/tdef/NSTextCheckingType
所以我建议你使用正则表达式。 这就像是:
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。
答案 3 :(得分:4)
这是一个干净的Swift版本。
extension String {
func isValidEmail() -> Bool {
guard !self.lowercaseString.hasPrefix("mailto:") else { return false }
guard let emailDetector = try? NSDataDetector(types: NSTextCheckingType.Link.rawValue) else { return false }
let matches = emailDetector.matchesInString(self, options: NSMatchingOptions.Anchored, range: NSRange(location: 0, length: self.characters.count))
guard matches.count == 1 else { return false }
return matches[0].URL?.absoluteString == "mailto:\(self)"
}
}
Swift 3.0版本:
extension String {
func isValidEmail() -> Bool {
guard !self.lowercased().hasPrefix("mailto:") else { return false }
guard let emailDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else { return false }
let matches = emailDetector.matches(in: self, options: NSRegularExpression.MatchingOptions.anchored, range: NSRange(location: 0, length: self.characters.count))
guard matches.count == 1 else { return false }
return matches[0].url?.absoluteString == "mailto:\(self)"
}
}
<强>目标-C:强>
@implementation NSString (EmailValidator)
- (BOOL)isValidEmail {
if ([self.lowercaseString hasPrefix:@"mailto:"]) { return NO; }
NSDataDetector* dataDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
if (dataDetector == nil) { return NO; }
NSArray* matches = [dataDetector matchesInString:self options:NSMatchingAnchored range:NSMakeRange(0, [self length])];
if (matches.count != 1) { return NO; }
NSTextCheckingResult* match = [matches firstObject];
return match.resultType == NSTextCheckingTypeLink && [match.URL.absoluteString isEqualToString:[NSString stringWithFormat:@"mailto:%@", self]];
}
@end
答案 4 :(得分:0)
看来探测器现在适用于电子邮件?
let types = [NSTextCheckingType.Link, NSTextCheckingType.PhoneNumber] as NSTextCheckingType
responseAttributedLabel.enabledTextCheckingTypes = types.rawValue
我可以点击电子邮件。我虽然使用TTTAttributedLabel。
答案 5 :(得分:-1)
这是Swift 1.2中的电子邮件示例。可能不会检查所有边缘情况,但它是一个很好的起点。
func isEmail(emailString : String)->Bool {
// need optional - will be nil if successful
var error : NSError?
// use countElements() with Swift 1.1
var textRange = NSMakeRange(0, count(emailString))
// Link type includes email (mailto)
var detector : NSDataDetector = NSDataDetector(types: NSTextCheckingType.Link.rawValue, error: &error)!
if error == nil {
// options value is ignored for this method, but still required!
var result = detector.firstMatchInString(emailString, options: NSMatchingOptions.Anchored, range: textRange)
if result != nil {
// check range to make sure a substring was not detected
return result!.URL!.scheme! == "mailto" && (result!.range.location == textRange.location) && (result!.range.length == textRange.length)
}
} else {
// handle error
}
return false
}
let validEmail = isEmail("someone@site.com") // returns true