4

I am using the following regular expression for email validation:

NSString *emailRegEx = @"([0-9a-zA-Z]([-.[A-Za-z0-9_]]*[0-9a-zA-Z_])*@([0-9a-zA-Z][-[A-Za-z0-9_]]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})";
NSPredicate *emailRegexPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", firstPartRegex];
return [emailRegexPredicate evaluateWithObject:input]

The problem I'm having is that iPhone is hanging when I enter an invalid email that has about 20-25+ characters before the @ symbol.

For example, the email address "Abcdefghijklmnopqrstuvwxyz@gmail" will cause iPhone to hang. but "Abcdefghijklmnopqrstuvwxyz@gmail.com" will validate normally. "Abcdefghijklmnopqrst@gmail" will return invalid immediately.

I notice around 20 characters that it will take longer for regex to return invalid, then incrementing by 1 character will take seemingly exponentially longer.

It seems that it has something to do with this part of the expression:

([-.[A-Za-z0-9_]]*[0-9a-zA-Z_])*

but I can't come up with an alternative that gives the same result.

Any ideas?

4

1 回答 1

3

github 上有一个项目,它有一个经过良好测试的电子邮件正则表达式 - 自己制作一个非常非常困难 - 请参阅此链接以测试各种模式。该项目有一个isValidEmail可以迭代调用的方法(比如用户在信息中点击),因此您可以启用提交按钮等。

您还可以在此先前的答案中阅读有关该问题和其他解决方案的更多信息。

编辑:regEx 中的歧义似乎会导致需要无限时间才能解决的循环。自从发布这个答案以来,我一直在研究一个“近乎完美”的正则表达式来验证电子邮件,所有这些都基于标准。github项目也更新了,验证RegEx为:

@"^(?:(?:(?:(?: ) (?:(?:(?:\t| ) \r\n)?(?:\t| )+))+(?: ) )|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&' +/=?^ {|}~]+(?:\\.[-A-Za-z0-9!#$%&'*+/=?^_{|}~]+)*)|(? :\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\[|\])|(?:\\(?:\t |[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:A-Za-z0-9?) (?:\.A-Za-z0-9?)*)|(?:\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9)) ][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]) )\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?: 2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(? : )*)|(?:[Vv][0-9A-Fa-f]+\.[-A-Za-z0-9. ~!$&'() +,;=:]+))\ ])))(?:(?:(?:(?: ) (?:(?:(?:\t| ) \r\n)?(?:\t| )+))+(?: ) )|(?: )+)?$"

于 2013-05-13T20:57:51.350 回答