Regex hangs on iPhone to check email

I use the following regular expression to validate email:

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 am facing is that the iPhone hangs when I enter an invalid email with 20-25 + characters before the @ character.

For example, the email address " Abcdefghijklmnopqrstuvwxyz@gmail " will cause the iPhone to freeze. but " Abcdefghijklmnopqrstuvwxyz@gmail.com " will be checked normally. " Abcdefghijklmnopqrst@gmail " will return immediately.

I notice about 20 characters that it will take longer for the regular expression to return the value invalid, and then an increase of 1 character will look exponentially longer.

This seems to have 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
source share
1 answer

There is a github project that has a well-tested regular expression for email - it is very difficult to create it yourself - see this link for testing various templates . The project has an isValidEmail method, which you can name iteratively (for example, the user enters information), so you can enable the "Submit" button, etc.

More information about the problem and other solutions can be found in this previous answer .

EDIT: It seems that the ambiguity in regEx can lead to loops that take infinite time to solve. After posting this answer, I worked on an β€œalmost perfect” email check register, all based on the standard. The github project is also updated, and the RegEx check:

@ "^ (? :(? :(? :(? :) (?: (?: (?: \ 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-] + \ [- A-Za-z0-9 ~ $ & '() +, =:.!] ?. +)) \]))) (? :(? :(? :( ?:) (&: (?: (&: \ t |) \ r \ n)? (?: \ t |) +)) + (? :)) | (? :) +)? $ "

+3
source

Source: https://habr.com/ru/post/1480583/


All Articles