Reputation: 11
I am trying to validate emails according to the RFC 5322 standard. I have been using the following C# expression
^(?(")(".+?(?<!\\)"@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$
Taken from http://emailregex.com/, but whenever I attempt to use this email in my Objective C ios application I am getting errors
Can someone help me with how this expression could be improved so that I am able to match validate that emails match the RFC 5322 standard? Keep in mind this means that not only domains but ip address email need to be accepted as well, both in and out of square brackets.
Upvotes: 1
Views: 286
Reputation: 437381
When you put this regex pattern in a string literal, you have to escape every "
and \
character with another \
. Thus, every "
becomes \"
and every \
becomes \\
.
Unfortunately, even after you fix that, that C# rendition doesn't work with NSRegularExpression
. But when I grabbed the RFC 5322 Official Standard from that page you referenced, it worked after adding ^
at the start and $
at the end like you apparently did, and escaping all the "
and \
characters:
NSString *pattern = @"^(?:[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])+)\\])$";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
NSAssert(regex, @"Regex failed: %@", error);
Upvotes: 1
Reputation: 40
The previous answer is wrong. It is not because you are missing a closing bracket. XCode thinks you are missing a closing bracket because it is misinterpreting your quotations. As Rob said in the comments you need to reformat the expression wherever there are " or \
Upvotes: 0