tags:

views:

57

answers:

3

I have a regex issue that I need help with. Its trying to validate an Email address.

Regex rx = new Regex(@"^[A-Za-z0-9]([_\.\-]?[A-Za-z0-9]+)*\@[A-Za-z0-9]([_\.\-]?[A-Za-z0-9]+)*\.[A-Za-z0-9]([_\.\-]?[A-Za-z0-9]+)*$|^$");
rx.IsMatch("john.gilbert.stu.seattle.washington.us"); 

The IsMatch method never returns for that particular string. It goes into some infinite loop. Can anybody see what the problem is with the pattern.

Thanks!

+1  A: 

(some stuff)* is bad. See here: http://www.regular-expressions.info/catastrophic.html

Matt Connolly
A: 

I would recommend you the following to validate an email address:

try
{
    MailAddress addr = new MailAddress("[email protected]");
}
catch (FormatException exc)
{
    // The email address is not valid
}

Here's an interesting read.

Darin Dimitrov
I wish I could do this. Actually the regex is in an XSD file, which is used to validate big XML documents. To isolate my issue, I just took the part which had the problem, and wrote that quick test method above.
Rohit Agarwal
+1 for an interesting read, -1 for suggesting using exceptions in a non-exceptional circumstance.
jloubert
@jloubert How do you know it's non-exceptional? If the circumstance was a method expected to send a mail to the address passed, then it's exceptional as there is no possible way to succeed at that point.
Jon Hanna
Good point -- if there was, say, a `Validate()` method and a `SendEmail()` method, this solution would be fine for `SendEmail()`; `Validate()` should have already caught any bad data, so an exception would be warranted. However, if the point of this question is to code the `Validate()` method itself, I would frown on this, because we can probably expect to get invalid data and handle it easily without resorting to an exception.
jloubert
A: 

The first "+" is the problem, if you remove it it runs

Quinn351
Awesome! Thanks Quinn.
Rohit Agarwal
Actually, the plus signs are fine--in fact, you need more of them. It's the question marks that don't belong. `^[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*@[A-Za-z0-9]+([_.-][A-Za-z0-9]+)*$`
Alan Moore