验证iOS 2.0上的电子邮件地址的最佳做法是什么

时间:2022-09-01 20:06:51

What is the cleanest way to validate an email address that a user enters on iOS 2.0?

验证用户在iOS 2.0上输入的电子邮件地址的最简洁方法是什么?

NOTE: This is a historical question that is specific to iOS 2.0 and due to its age and how many other questions are linked to it it cannot be retired and MUST NOT be changed to a "modern" question.

注意:这是一个特定于iOS 2.0的历史问题,由于其年龄和与其相关的其他问题,它不能退役,不能改为“现代”问题。

13 个解决方案

#1


The answer to Using a regular expression to validate an email address explains in great detail that the grammar specified in RFC 5322 is too complicated for primitive regular expressions.

使用正则表达式验证电子邮件地址的答案非常详细地解释了RFC 5322中指定的语法对于原始正则表达式而言过于复杂。

I recommend a real parser approach like MKEmailAddress.

我推荐像MKEmailAddress这样的真正的解析器方法。

As quick regular expressions solution see this modification of DHValidation:

作为快速正则表达式解决方案,请参阅DHValidation的此修改:

- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex =
@"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
@"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
@"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
@"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
@"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
@"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
@"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@", emailRegex]; 

    return [emailTest evaluateWithObject:candidate];
}

#2


Read the RFC. Almost everyone that thinks they know how to parse/clean/validate an email address is wrong.

阅读RFC。几乎每个认为他们知道如何解析/清理/验证电子邮件地址的人都是错误的。

http://tools.ietf.org/html/rfc2822 Section 3.4.1 is very useful. Notice

http://tools.ietf.org/html/rfc2822第3.4.1节非常有用。注意

dtext           =       NO-WS-CTL /     ; Non white space controls

                        %d33-90 /       ; The rest of the US-ASCII
                        %d94-126        ;  characters not including "[",
                                        ;  "]", or "\"

Yes, that means +, ', etc are all legit.

是的,这意味着+,'等都是合法的。

#3


The best solution I have found so far (and the one I ended up going with) is to add RegexKitLite To the project which gives access to regular expressions via NSString Categories.

到目前为止我找到的最好的解决方案(以及我最终得到的解决方案)是将RegexKitLite添加到项目中,该项目通过NSString Categories提供对正则表达式的访问。

It is quite painless to add to the project and once in place, any of the regular expression email validation logic will work.

添加到项目中非常轻松,一旦到位,任何正则表达式电子邮件验证逻辑都将起作用。

#4


A good start is to decide what do you and do you not want to accept as an email address?

一个好的开始是决定你和你不想接受什么作为电子邮件地址?

99% of of email addresses look like this: bob.smith@foo.com or fred@bla.edu

99%的电子邮件地址如下所示:bob.smith@foo.com或fred@bla.edu

However, it's technically legal to have an email address like this: f!#$%&'*+-/=?^_{|}~"ha!"@com

但是,拥有这样的电子邮件地址在技术上是合法的:f!#$%&'* + - / =?^ _ {|}〜“ha!”@ com

There are probably only a handful of valid emails in the world for top-level domains, and almost nobody uses most of those other characters (especially quotes and backticks), so you might want to assume that these are all invalid things to do. But you should do so as a conscious decision.

对于*域名,世界上可能只有少数有效的电子邮件,而且几乎没有人使用其他大多数字符(特别是引号和反引号),所以你可能想要假设这些都是无效的事情。但你应该这样做是有意识的决定。

Beyond that, do what Paul says and try to match the input to a regular expression like this: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}$

除此之外,做Paul所说的并尝试将输入与正则表达式匹配如下:^ [A-Z0-9 ._%+ - ] + @ [A-Z0-9 .-] +。[AZ] { 2,} $

That one will match pretty much everybody's email address.

那个人几乎会匹配每个人的电子邮件地址。

#5


While the focus on regular expressions is good, but this is only a first and necessary step. There are other steps that also need to be accounted for a good validation strategy.

虽然对正则表达式的关注很好,但这只是第一个必要的步骤。还有其他步骤也需要考虑一个好的验证策略。

Two things on top of my head are :

我头顶的两件事是:

  1. DNS validation to make sure the domain actually exists.

    DNS验证以确保域实际存在。

  2. After dns validation, you can also choose to do an smtp validation. send a call to the smtp server to see if the user actually exists.

    在DNS验证之后,您还可以选择执行smtp验证。向smtp服务器发送呼叫以查看用户是否确实存在。

In this way you can catch all kinds of user errors and make sure it is a valid email.

通过这种方式,您可以捕获各种用户错误并确保它是有效的电子邮件。

#6


This function is simple and yet checks email address more thoroughly. For example, according to RFC2822 an email address must not contain two periods in a row, such as firstname..lastname@domain..com

此功能很简单,但更彻底地检查电子邮件地址。例如,根据RFC2822,电子邮件地址不得包含连续的两个句点,例如firstname..lastname @ domain..com

It is also important to use anchors in regular expressions as seen in this function. Without anchors the following email address is considered valid: first;name)lastname@domain.com(blah because the lastname@domain.com section is valid, ignoring first;name) at the beginning and (blah at the end. Anchors force the regular expressions engine to validate the entire email.

在正则表达式中使用锚也很重要,如此函数中所示。没有锚点,以下电子邮件地址被认为是有效的:第一个;名称)lastname@domain.com(因为lastname@domain.com部分是有效的,首先忽略;名称),在开头和(等等)。锚点强制正则表达式引擎来验证整个电子邮件。

This function uses NSPredicate which does not exist in iOS 2. Unfortunately it may not help the asker, but hopefully will help others with newer versions of iOS. The regular expressions in this function can still be applied to RegExKitLite in iOS 2 though. And for those using iOS 4 or later, these regular expressions can be implemented with NSRegularExpression.

此功能使用NSPredicate,这在iOS 2中不存在。不幸的是,它可能无法帮助提问者,但希望能帮助其他人使用更新版本的iOS。此函数中的正则表达式仍然可以应用于iOS 2中的RegExKitLite。对于使用iOS 4或更高版本的用户,可以使用NSRegularExpression实现这些正则表达式。

- (BOOL)isValidEmail:(NSString *)email
{
    NSString *regex1 = @"\\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,4}\\z";
    NSString *regex2 = @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*";
    NSPredicate *test1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
    NSPredicate *test2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
    return [test1 evaluateWithObject:email] && [test2 evaluateWithObject:email];
}

See validate email address using regular expression in Objective-C.

请参阅使用Objective-C中的正则表达式验证电子邮件地址。

#7


NSString *emailString = textField.text; **// storing the entered email in a string.** 
**// Regular expression to checl the email format.** 
NSString *emailReg = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailReg]; 
if (([emailTest evaluateWithObject:emailString] != YES) || [emailStringisEqualToString:@""]) 
{ 
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:@" Enter Email in" message:@"abc@example.com format" delegate:self 
cancelButtonTitle:@"OK" otherButtonTitles:nil]; 

enter code here

[loginalert show]; 
[loginalert release]; 
} 
If email is invalid, it will remind the user with an alert box. 
Hope this might be helpful for you all. 

#8


I have found that using a regular expression works quite well to validate an email address.

我发现使用正则表达式可以很好地验证电子邮件地址。

The major downside to regular expressions of course is maintainability, so comment like you have never commented before. I promise you, if you don't you will wish you did when you go back to the expression after a few weeks.

当然,正则表达式的主要缺点是可维护性,因此您之前从未评论过评论。我保证,如果你不这样做,你会希望你在几周之后回到表达时做。

Here is a link to a good source, http://www.regular-expressions.info/email.html.

这是一个很好的来源链接,http://www.regular-expressions.info/email.html。

#9


Digging up the dirt, but I just stumbled upon SHEmailValidator which does a perfect job and has a nice interface.

挖掘污垢,但我偶然发现了SHEmailValidator,它完美的工作,并有一个很好的界面。

#10


Many web sites provide RegExes but you'd do well to learn and understand them as well as verify that what you want it to do meets your needs within the official RFC for email address formats.

许多网站提供RegExes,但您最好学习和理解它们,并验证您希望它做什么,在官方RFC中为电子邮件地址格式满足您的需求。

For learning RegEx, interpreted languages can be a great simplifier and testbed. Rubular is built on Ruby, but is a good quick way to test and verify: http://www.rubular.com/

为了学习RegEx,解释语言可以是一个很好的简化和测试平台。 Rubular是基于Ruby构建的,但它是一种快速测试和验证的方法:http://www.rubular.com/

Beyond that, buy the latest edition of the O'Reilly book Mastering Regular Expressions. You'll want to spend the time to understand the first 3 or 4 chapters. Everything after that will be building expertise on highly optimized RegEx usage.

除此之外,购买最新版本的O'Reilly书籍Mastering Regular Expressions。您需要花时间了解前3或4章。之后的一切将是建立高度优化的RegEx使用的专业知识。

Often a series of smaller, easier to manage RegExes are easier to maintain and debug.

通常,一系列更小,更易于管理的RegExs更易于维护和调试。

#11


Here is an extension of String that validates an email in Swift.

这是String的扩展,用于验证Swift中的电子邮件。

extension String {

    func isValidEmail() -> Bool {
        let stricterFilter = false
        let stricterFilterString = "^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$"
        let laxString = "^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$"
        let emailRegex = stricterFilter ? stricterFilterString : laxString
        let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        return emailTest.evaluate(with: self)
    }
}

Copied from the answer to: Check that an email address is valid on iOS

从答案中复制:检查iOS上的电子邮件地址是否有效

#12


You shouldn't try to use regex to validate an email. With ever changing TLDs, your validator is either incomplete or inaccurate. Instead, you should leverage Apple's NSDataDetector libraries which will take a string and try to see if there are any known data fields (emails, addresses, dates, etc). Apple's SDK will do the heavy lifting of keeping up to date with TLDs and you can piggyback off of their efforts!! :)

您不应该尝试使用正则表达式来验证电子邮件。随着TLD的不断变化,您的验证器要么不完整,要么不准确。相反,您应该利用Apple的NSDataDetector库,它将获取一个字符串并尝试查看是否有任何已知的数据字段(电子邮件,地址,日期等)。 Apple的SDK将尽最大努力与TLD保持同步,您可以捎带他们的努力! :)

Plus, if iMessage (or any other text field) doesn't think it's an email, should you consider an email?

另外,如果iMessage(或任何其他文本字段)认为它不是电子邮件,您是否应该考虑发送电子邮件?

I put this function in a NSString category, so the string you're testing is self.

我将此函数放在NSString类别中,因此您正在测试的字符串是self。

- (BOOL)isValidEmail {
    // Trim whitespace first
    NSString *trimmedText = [self stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
    if (self && self.length > 0) return NO;

    NSError *error = nil;
    NSDataDetector *dataDetector = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:&error];
    if (!dataDetector) return NO;

    // This string is a valid email only if iOS detects a mailto link out of the full string
    NSArray<NSTextCheckingResult *> *allMatches = [dataDetector matchesInString:trimmedText options:kNilOptions range:NSMakeRange(0, trimmedText.length)];
    if (error) return NO;
    return (allMatches.count == 1 && [[[allMatches.firstObject URL] absoluteString] isEqual:[NSString stringWithFormat:@"mailto:%@", self]]);
}

or as a swift String extension

或者作为swift String扩展

extension String {
    func isValidEmail() -> Bool {
        let trimmed = self.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty, let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
            return false
        }
        let allMatches = dataDetector.matches(in: trimmed, options: [], range: NSMakeRange(0, trimmed.characters.count))

        return allMatches.count == 1 && allMatches.first?.url?.absoluteString == "mailto:\(trimmed)"
    }
}

#13


// Method Call
NSString *email = @"Your Email string..";

BOOL temp = [self validateEmail:email];

if(temp)
{
// Valid
}
else
{
// Not Valid
}
// Method description

- (BOOL) validateEmail: (NSString *) email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    BOOL isValid = [emailTest evaluateWithObject:email];
    return isValid;
}

#1


The answer to Using a regular expression to validate an email address explains in great detail that the grammar specified in RFC 5322 is too complicated for primitive regular expressions.

使用正则表达式验证电子邮件地址的答案非常详细地解释了RFC 5322中指定的语法对于原始正则表达式而言过于复杂。

I recommend a real parser approach like MKEmailAddress.

我推荐像MKEmailAddress这样的真正的解析器方法。

As quick regular expressions solution see this modification of DHValidation:

作为快速正则表达式解决方案,请参阅DHValidation的此修改:

- (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex =
@"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
@"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
@"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
@"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
@"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
@"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
@"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@", emailRegex]; 

    return [emailTest evaluateWithObject:candidate];
}

#2


Read the RFC. Almost everyone that thinks they know how to parse/clean/validate an email address is wrong.

阅读RFC。几乎每个认为他们知道如何解析/清理/验证电子邮件地址的人都是错误的。

http://tools.ietf.org/html/rfc2822 Section 3.4.1 is very useful. Notice

http://tools.ietf.org/html/rfc2822第3.4.1节非常有用。注意

dtext           =       NO-WS-CTL /     ; Non white space controls

                        %d33-90 /       ; The rest of the US-ASCII
                        %d94-126        ;  characters not including "[",
                                        ;  "]", or "\"

Yes, that means +, ', etc are all legit.

是的,这意味着+,'等都是合法的。

#3


The best solution I have found so far (and the one I ended up going with) is to add RegexKitLite To the project which gives access to regular expressions via NSString Categories.

到目前为止我找到的最好的解决方案(以及我最终得到的解决方案)是将RegexKitLite添加到项目中,该项目通过NSString Categories提供对正则表达式的访问。

It is quite painless to add to the project and once in place, any of the regular expression email validation logic will work.

添加到项目中非常轻松,一旦到位,任何正则表达式电子邮件验证逻辑都将起作用。

#4


A good start is to decide what do you and do you not want to accept as an email address?

一个好的开始是决定你和你不想接受什么作为电子邮件地址?

99% of of email addresses look like this: bob.smith@foo.com or fred@bla.edu

99%的电子邮件地址如下所示:bob.smith@foo.com或fred@bla.edu

However, it's technically legal to have an email address like this: f!#$%&'*+-/=?^_{|}~"ha!"@com

但是,拥有这样的电子邮件地址在技术上是合法的:f!#$%&'* + - / =?^ _ {|}〜“ha!”@ com

There are probably only a handful of valid emails in the world for top-level domains, and almost nobody uses most of those other characters (especially quotes and backticks), so you might want to assume that these are all invalid things to do. But you should do so as a conscious decision.

对于*域名,世界上可能只有少数有效的电子邮件,而且几乎没有人使用其他大多数字符(特别是引号和反引号),所以你可能想要假设这些都是无效的事情。但你应该这样做是有意识的决定。

Beyond that, do what Paul says and try to match the input to a regular expression like this: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,}$

除此之外,做Paul所说的并尝试将输入与正则表达式匹配如下:^ [A-Z0-9 ._%+ - ] + @ [A-Z0-9 .-] +。[AZ] { 2,} $

That one will match pretty much everybody's email address.

那个人几乎会匹配每个人的电子邮件地址。

#5


While the focus on regular expressions is good, but this is only a first and necessary step. There are other steps that also need to be accounted for a good validation strategy.

虽然对正则表达式的关注很好,但这只是第一个必要的步骤。还有其他步骤也需要考虑一个好的验证策略。

Two things on top of my head are :

我头顶的两件事是:

  1. DNS validation to make sure the domain actually exists.

    DNS验证以确保域实际存在。

  2. After dns validation, you can also choose to do an smtp validation. send a call to the smtp server to see if the user actually exists.

    在DNS验证之后,您还可以选择执行smtp验证。向smtp服务器发送呼叫以查看用户是否确实存在。

In this way you can catch all kinds of user errors and make sure it is a valid email.

通过这种方式,您可以捕获各种用户错误并确保它是有效的电子邮件。

#6


This function is simple and yet checks email address more thoroughly. For example, according to RFC2822 an email address must not contain two periods in a row, such as firstname..lastname@domain..com

此功能很简单,但更彻底地检查电子邮件地址。例如,根据RFC2822,电子邮件地址不得包含连续的两个句点,例如firstname..lastname @ domain..com

It is also important to use anchors in regular expressions as seen in this function. Without anchors the following email address is considered valid: first;name)lastname@domain.com(blah because the lastname@domain.com section is valid, ignoring first;name) at the beginning and (blah at the end. Anchors force the regular expressions engine to validate the entire email.

在正则表达式中使用锚也很重要,如此函数中所示。没有锚点,以下电子邮件地址被认为是有效的:第一个;名称)lastname@domain.com(因为lastname@domain.com部分是有效的,首先忽略;名称),在开头和(等等)。锚点强制正则表达式引擎来验证整个电子邮件。

This function uses NSPredicate which does not exist in iOS 2. Unfortunately it may not help the asker, but hopefully will help others with newer versions of iOS. The regular expressions in this function can still be applied to RegExKitLite in iOS 2 though. And for those using iOS 4 or later, these regular expressions can be implemented with NSRegularExpression.

此功能使用NSPredicate,这在iOS 2中不存在。不幸的是,它可能无法帮助提问者,但希望能帮助其他人使用更新版本的iOS。此函数中的正则表达式仍然可以应用于iOS 2中的RegExKitLite。对于使用iOS 4或更高版本的用户,可以使用NSRegularExpression实现这些正则表达式。

- (BOOL)isValidEmail:(NSString *)email
{
    NSString *regex1 = @"\\A[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,4}\\z";
    NSString *regex2 = @"^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*";
    NSPredicate *test1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex1];
    NSPredicate *test2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex2];
    return [test1 evaluateWithObject:email] && [test2 evaluateWithObject:email];
}

See validate email address using regular expression in Objective-C.

请参阅使用Objective-C中的正则表达式验证电子邮件地址。

#7


NSString *emailString = textField.text; **// storing the entered email in a string.** 
**// Regular expression to checl the email format.** 
NSString *emailReg = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",emailReg]; 
if (([emailTest evaluateWithObject:emailString] != YES) || [emailStringisEqualToString:@""]) 
{ 
UIAlertView *loginalert = [[UIAlertView alloc] initWithTitle:@" Enter Email in" message:@"abc@example.com format" delegate:self 
cancelButtonTitle:@"OK" otherButtonTitles:nil]; 

enter code here

[loginalert show]; 
[loginalert release]; 
} 
If email is invalid, it will remind the user with an alert box. 
Hope this might be helpful for you all. 

#8


I have found that using a regular expression works quite well to validate an email address.

我发现使用正则表达式可以很好地验证电子邮件地址。

The major downside to regular expressions of course is maintainability, so comment like you have never commented before. I promise you, if you don't you will wish you did when you go back to the expression after a few weeks.

当然,正则表达式的主要缺点是可维护性,因此您之前从未评论过评论。我保证,如果你不这样做,你会希望你在几周之后回到表达时做。

Here is a link to a good source, http://www.regular-expressions.info/email.html.

这是一个很好的来源链接,http://www.regular-expressions.info/email.html。

#9


Digging up the dirt, but I just stumbled upon SHEmailValidator which does a perfect job and has a nice interface.

挖掘污垢,但我偶然发现了SHEmailValidator,它完美的工作,并有一个很好的界面。

#10


Many web sites provide RegExes but you'd do well to learn and understand them as well as verify that what you want it to do meets your needs within the official RFC for email address formats.

许多网站提供RegExes,但您最好学习和理解它们,并验证您希望它做什么,在官方RFC中为电子邮件地址格式满足您的需求。

For learning RegEx, interpreted languages can be a great simplifier and testbed. Rubular is built on Ruby, but is a good quick way to test and verify: http://www.rubular.com/

为了学习RegEx,解释语言可以是一个很好的简化和测试平台。 Rubular是基于Ruby构建的,但它是一种快速测试和验证的方法:http://www.rubular.com/

Beyond that, buy the latest edition of the O'Reilly book Mastering Regular Expressions. You'll want to spend the time to understand the first 3 or 4 chapters. Everything after that will be building expertise on highly optimized RegEx usage.

除此之外,购买最新版本的O'Reilly书籍Mastering Regular Expressions。您需要花时间了解前3或4章。之后的一切将是建立高度优化的RegEx使用的专业知识。

Often a series of smaller, easier to manage RegExes are easier to maintain and debug.

通常,一系列更小,更易于管理的RegExs更易于维护和调试。

#11


Here is an extension of String that validates an email in Swift.

这是String的扩展,用于验证Swift中的电子邮件。

extension String {

    func isValidEmail() -> Bool {
        let stricterFilter = false
        let stricterFilterString = "^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$"
        let laxString = "^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$"
        let emailRegex = stricterFilter ? stricterFilterString : laxString
        let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        return emailTest.evaluate(with: self)
    }
}

Copied from the answer to: Check that an email address is valid on iOS

从答案中复制:检查iOS上的电子邮件地址是否有效

#12


You shouldn't try to use regex to validate an email. With ever changing TLDs, your validator is either incomplete or inaccurate. Instead, you should leverage Apple's NSDataDetector libraries which will take a string and try to see if there are any known data fields (emails, addresses, dates, etc). Apple's SDK will do the heavy lifting of keeping up to date with TLDs and you can piggyback off of their efforts!! :)

您不应该尝试使用正则表达式来验证电子邮件。随着TLD的不断变化,您的验证器要么不完整,要么不准确。相反,您应该利用Apple的NSDataDetector库,它将获取一个字符串并尝试查看是否有任何已知的数据字段(电子邮件,地址,日期等)。 Apple的SDK将尽最大努力与TLD保持同步,您可以捎带他们的努力! :)

Plus, if iMessage (or any other text field) doesn't think it's an email, should you consider an email?

另外,如果iMessage(或任何其他文本字段)认为它不是电子邮件,您是否应该考虑发送电子邮件?

I put this function in a NSString category, so the string you're testing is self.

我将此函数放在NSString类别中,因此您正在测试的字符串是self。

- (BOOL)isValidEmail {
    // Trim whitespace first
    NSString *trimmedText = [self stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
    if (self && self.length > 0) return NO;

    NSError *error = nil;
    NSDataDetector *dataDetector = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:&error];
    if (!dataDetector) return NO;

    // This string is a valid email only if iOS detects a mailto link out of the full string
    NSArray<NSTextCheckingResult *> *allMatches = [dataDetector matchesInString:trimmedText options:kNilOptions range:NSMakeRange(0, trimmedText.length)];
    if (error) return NO;
    return (allMatches.count == 1 && [[[allMatches.firstObject URL] absoluteString] isEqual:[NSString stringWithFormat:@"mailto:%@", self]]);
}

or as a swift String extension

或者作为swift String扩展

extension String {
    func isValidEmail() -> Bool {
        let trimmed = self.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty, let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
            return false
        }
        let allMatches = dataDetector.matches(in: trimmed, options: [], range: NSMakeRange(0, trimmed.characters.count))

        return allMatches.count == 1 && allMatches.first?.url?.absoluteString == "mailto:\(trimmed)"
    }
}

#13


// Method Call
NSString *email = @"Your Email string..";

BOOL temp = [self validateEmail:email];

if(temp)
{
// Valid
}
else
{
// Not Valid
}
// Method description

- (BOOL) validateEmail: (NSString *) email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    BOOL isValid = [emailTest evaluateWithObject:email];
    return isValid;
}