Jason94
Jason94

Reputation: 13610

Why does my regex fail to match email?

I have to following code to validate an email address

 var reg = new Regex(@"/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/");

 string e1 = "[email protected]";
 string e2 = "namehost.net";

 bool b1 = reg.IsMatch(e1);
 bool b2 = reg.IsMatch(e2);

but both b1 and b2 fail

Upvotes: 0

Views: 134

Answers (1)

Lucero
Lucero

Reputation: 60190

Remove the slashes at the beginning and end.

var reg = new Regex(@"^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$");

However, that being said, your regex is not a good pattern for matching e-mail addresses. In fact, an accurate pattern is really difficult to make. Google some and you should find better ones.

Upvotes: 3

Related Questions