1

We are using regex to validate Emails. But it seems like it is failing for abcd@q.com this Email ID. Can anyone please advise what is wrong in the given regex?

Regular Expression:

string sPattern = "^\\w+[\\w\\-\\.]*\\w+\\@\\w+([\\w\\-]*\\w+\\.\\w+){1,4}$";

Edit: what can I modify in the given regex so that it should accept both single character and multiple character domain after @.

Ex: abcd@q.com or abcd@example.com

3 Answers3

1
\w+([\\w\\-]*\\w+

In this part, you want, between the @ and the .

  • at least one alphanumeric char => w+
  • 0 or more alphanumeric char or - => [\\w\\-]*
  • at least one alphanumeric char => w+

So as you have only one char q, the check fails miserably.

You should search for existing e-mail validation patterns, it's rather complicated !

Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
0
bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);
huse.ckr
  • 530
  • 12
  • 39
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – J. Chomel Sep 23 '16 at 08:49
0

You should look up existing regexes for email validation. But what I can tell from your regex is that you have many unnecessary "\w"s. Removing them:

^[\w\-\.]+\@([\w\-]+\.\w+){1,4}$

Will have a working regex. Though not a very accurate one for email validation

Tyress
  • 3,573
  • 2
  • 22
  • 45