0

Possible Duplicate:
Using a regular expression to validate an email address
Email Validation - Regular Expression

I am using following code to validate Email address in C#, but not sure why it fails always:

 var regEx = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})";

        if (Regex.IsMatch(regEx, "abcde@gmail.com", RegexOptions.IgnoreCase))
            return true;
        else
            return false;

Please can someone point out what I am missing here ?

Community
  • 1
  • 1
RMN
  • 754
  • 9
  • 25
  • 45
  • [regexp-based address validation](http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html) – L.B Nov 12 '12 at 11:30
  • This is not a duplicate. The question is not "how to validate an email address", it is "why does this (already defined) regex not match". – Stefan Steinegger Nov 12 '12 at 13:09
  • I am not sure why the question was closed. I had an issue that why regex is not working and answer was incorrect format used plus using var to declare instead of string. I did not ask for regular expression pattern ! – RMN Nov 12 '12 at 14:50

2 Answers2

2

Try this:

[Test]
public void EmailTest()
{
    var pattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})";
    Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
    var address = "abcde@gmail.com";
    Assert.IsTrue(Regex.IsMatch(address, pattern,RegexOptions.IgnoreCase));
    Assert.IsTrue(regex.IsMatch(address));
}

You have the wrong order of string and pattern.

Also check this thread

Community
  • 1
  • 1
Johan Larsson
  • 17,112
  • 9
  • 74
  • 88
1

You've got your IsMatch parameters the wrong way around; the first is the input, the second is the pattern.

Rawling
  • 49,248
  • 7
  • 89
  • 127
  • Thanks for pointing out. I noticed that and modified my code, but still I get error. The best overload method match for System.text.regularexpression.regex.ismatch(string, int) has invalid arguments. – RMN Nov 12 '12 at 11:29
  • You should have `Regex.IsMatch("abcde@gmail.com", regEx, RegexOptions.IgnoreCase)` - is that what you have now? – Rawling Nov 12 '12 at 11:33
  • I had assigned pattern to var regEx in modified code, instead of String. It is working now. Thanks for help. – RMN Nov 12 '12 at 11:39