简体   繁体   中英

Does regex work differently with C#?

I'm trying to validate an e-mail string, and it seems like all public options I use in C# don't work at all An example, using the regex found in http://www.regular-expressions.info/email.html , i create a model with the following property:

[RegularExpression(@"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", ErrorMessage = "Please enter a valid email address.")]
    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "The Email address where we can reach you:")]
    public string Email { get; set; }

This always throws the error for some reason, even though it is just a straight copy from that website. I have the @ parameter in front of the regex, but are there other considerations i need to make in order to have this work in C#?

You need to allow lowercase letters too. Every time you have AZ you can change it to A-Za-z .

Note also that this regular expression rejects some valid email addresses, as explained on the site. For example, it rejects email addresses from the .museum top-level domain , to give just one example.

As referenced in the link you already provided:

http://www.regular-expressions.info/email.html

The regex that will supposedly validate against any RFC2822 email address is:

(?:[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])+)\])

Note that this regex will allow non-existent TLDs, but unless you want to be in the business of keeping up with new TLDs, I suggest you just go ahead and use this regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM