9

我有一个来自服务器的字符串,想检查它是否包含电话号码、邮件地址和电子邮件等表达式。我在电话号码和邮件地址的情况下取得了成功,但不是电子邮件。我正在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);
    }
}  

但是如何对电子邮件做同样的事情呢?

4

7 回答 7

32
if (result.resultType == NSTextCheckingTypeLink)
{
    if ([result.URL.scheme.locaseString isEqualToString:@"mailto"])
    {
        // email link
    }
    else
    {
        // url
    }
}

电子邮件地址属于 NSTextCheckingTypeLink。只需在找到的 URL 中查找“mailto:”,您就会知道它是电子邮件或 URL。

于 2013-07-18T11:05:07.603 回答
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"];
于 2012-08-30T11:12:15.887 回答
7

在苹果文档中,似乎识别的类型不包括电子邮件: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 得到了最好的解决方案,尽管我的解决方案是公认的,请阅读他的回答

于 2012-01-13T15:00:17.830 回答
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)"
    }
}

斯威夫特 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
于 2016-01-29T04:10:32.523 回答
0

似乎检测器现在适用于电子邮件?

let types = [NSTextCheckingType.Link, NSTextCheckingType.PhoneNumber] as NSTextCheckingType
responseAttributedLabel.enabledTextCheckingTypes = types.rawValue

我可以点击电子邮件。我正在使用 TTTAttributedLabel。

于 2016-10-20T17:34:21.350 回答
0

这是建立在 Dave Wood 和 mkto 答案之上的最新游乐场兼容版本:

import Foundation

func isValid(email: String) -> Bool {
  do {
    let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
    let range = NSRange(location: 0, length: email.count)
    let matches = detector.matches(in: email, options: .anchored, range: range)
    guard matches.count == 1 else { return false }
    return matches[0].url?.scheme == "mailto"
  } catch {
    return false
  }
}

extension String {
  var isValidEmail: Bool {
    isValid(email: self)
  }
}

let email = "test@mail.com"
isValid(email: email) // prints 'true'
email.isValidEmail // prints 'true'
于 2021-11-17T11:44:53.760 回答
-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
于 2015-02-14T20:43:04.457 回答