David
David

Reputation: 65

Regex - Detect Email address with - minus sign in FQDN

I have the following Regex to grab an email address out of a string. It works fantastic. However I noticed it fails if the domain name has a - character.

How can I allow minus characters in both the username portion of the email address as well as the domain portion of the email address?

For example: [email protected]

const string Pattern =
@"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";

Upvotes: -2

Views: 56

Answers (2)

John Shedletsky
John Shedletsky

Reputation: 7168

To allow hyphens (-) in both the local-part (before the @) and the domain labels (after the @), you need to update your character classes ([\w-]) to include the - explicitly wherever needed.

For example:

const string Pattern =
@"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"  // Local part allows - 
+ @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
+ @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ @"([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4})";          // Domain part allows -

Upvotes: 0

Artur Vasylkov
Artur Vasylkov

Reputation: 1

const string Pattern =
    @"(([\w-]+\.)+[\w-]+|([\w-]{1,}))@"
  + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
  + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
  + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
  + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9]))"
  + @"|(([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4}))";

this should do it

Upvotes: 0

Related Questions