0

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. xxx@yyy.zzz 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 )

Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254

4 Answers4

3

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
  • 43,259
  • 14
  • 84
  • 117
1

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
  • 166,582
  • 36
  • 299
  • 288
0

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;
}
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Teo
  • 11
  • 2
0

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
  • 2,199
  • 4
  • 20
  • 26