views:

208

answers:

6

I'm a complete newbie to RegEx and I'm sure it'll be brilliant to use once I know how to use it. :P

I have a couple of textBoxes and I was wondering if anyone could me acomplish what I need.

In the EMail textbox, I'd like to make sure the user writes in a valid email. [email protected] Is there a way for RegEx to help me out?

I'd also really like a way to format the name the user writes down. So if a user writes in "SerGIo TAPIA gutTIerrez I want to format that string (behind the scenes before saving it) to "Sergio Tapia Gutierrez" Can RegEx do this?

Thanks so much SO.

(inb4 Rex :P )

+3  A: 

A complete and accurate regex for email validation is surprisingly difficult, I trust you can use google to find some examples.

The general rule for email validation is to actually try to send an email.

Greg D
+2  A: 

See this SO question regarding validating email addresses.

And apparently there is a correct one here.

Cade Roux
A: 

Check regexlib.com.

Macarse
Intersting Gravatar. Kind of a subliminal push, eh?
Telemachus
hehe, it's actually from projecteuler :)
Macarse
A: 

http://www.cambiaresearch.com/c4/bf974b23-484b-41c3-b331-0bd8121d5177/Parsing-Email-Addresses-with-Regular-Expressions.aspx

public bool TestEmailRegex(string emailAddress)
{

//    string patternLenient = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
//    Regex reLenient = new Regex(patternLenient);

    string patternStrict = @"^(([^<>()[\]\\.,;:\s@""]+" 
        + @"(\.[^<>()[\]\\.,;:\s@""]+)*)|("".+""))@" 
        + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" 
        + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+" 
        + @"[a-zA-Z]{2,}))$";

    Regex reStrict = new Regex(patternStrict);

//    bool isLenientMatch = reLenient.IsMatch(emailAddress);
//    return isLenientMatch;

    bool isStrictMatch = reStrict.IsMatch(emailAddress);
    return isStrictMatch;
}
Teo
A: 

This is one way, but there are many others.

public static bool isEmail(string emailAddress)
{
   if(string.IsNullOrEmpty(emailAddress))
      return false;

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

   return EmailAddress.IsMatch(emailAddress);
}
J.Hendrix
+1  A: 

Well, this is an easy one! :)

  1. no, there exists no regex that can validate* e-mail addresses;
  2. no, regex cannot transform "SerGIo TAPIA gutTIerrez" into "Sergio Tapia Gutierrez". Sure, some language like Perl (and other perhaps) can mix-in some fancy stuff inside regex-es to do this, but it is not regex that actually performs the transformation. Regex only matches text, plain and simple.

* by 'valid' I mean see if the address actually exists.

Bart Kiers