Regular Expression to validate email ending in .edu

I am trying to create a regex validation attribute in asp.net mvc to validate that an entered email has the .edu TLD.

I have tried the following but the expression never validates to true...

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+edu

and

w.w@{1,1}w[.w]?.edu

Can anyone provide some insight?


This should work for you:

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.+-]+.edu$

Breakdown since you said you were weak at RegEx:

^ Beginning of string

[a-zA-Z0-9._%+-]+ one or more letters, numbers, dots, underscores, percent-signs, plus-signs or dashes

@ @

[a-zA-Z0-9.+-]+ one or more letters, numbers, dots, plus-signs or dashes

.edu .edu

$ End of string


if you're using asp.net mvc validation attributes, your regular expression actually has to be coded with javascript regex syntax, and not c# regex syntax. Some symbols are the same, but you have to be weary about that.

You want your attribute to look like the following:

 [RegularExpression(@"([0-9]|[a-z]|[A-Z])+@([0-9]|[a-z]|[A-Z])+.edu$", ErrorMessage = "text to display to user")]

the reason you include the @ before the string is to make a literal string, because I believe c# will apply its own escape sequences before it passes it to the regex

(a|b|c) matches either an 'a' or 'b' or 'c'. [az] matches all characters between a and z, and the similar for capital letters and numerals so, ([0-9]|[az]|[AZ]) matches any alphanumeric character

([0-9]|[az]|[AZ])+ matches 1 or more alphanumeric characters. + in a regular expression means 1 or more of the previous

@ is for the '@' symbol in an email address. If it doesn't work, you might have to escape it, but i don't know of any special meaning for @ in a javascript regex

Let's simplify it more

[RegularExpression(@"w+@w+.edu$", ErrorMessage = "text to display to user")]

w stands for any alphanumeric character including underscore

read some regex documentation at https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions for more information


try this:

Regex regex = new Regex(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+.(edu)$", RegexOptions.IgnoreCase);

ANSWER UPDATED...

链接地址: http://www.djcxy.com/p/92876.html

上一篇: 将短划线添加到Java正则表达式

下一篇: 正则表达式来验证以.edu结尾的电子邮件