TrackmeifYouCan
TrackmeifYouCan

Reputation: 108

How to replace email address with name in text using regular expressions in C#?

how can I replace the email addresses in a paragraph assuming it's a string now, with names ? like [email protected] = xx , .com, .ae

Input = "contact [email protected] or [email protected] for more details"

Output = "contact Abc or Defg for more details"

Upvotes: 2

Views: 5215

Answers (4)

user1449936
user1449936

Reputation: 21

public static string ReplaceEmail(string emailBody) {
        string scrubbedemailBody = emailBody;
        Regex regex = new Regex(@"(\.|[a-z]|[A-Z]|[0-9])*@(\.|[a-z]|[A-Z]|[0-9])*");
        scrubbedemailBody = regex.Replace(scrubbedemailBody, match => {
            return new string(' ', match.Length);
        });
        return scrubbedemailBody;
    }

Upvotes: 0

Nolonar
Nolonar

Reputation: 6122

Since you're asking for a Regex, I'm going to give you one.

Regex regex = new Regex(@"(\.|[a-z]|[A-Z]|[0-9])*@(\.|[a-z]|[A-Z]|[0-9])*");
foreach (Match match in regex.Matches(inputString))
{
    // match.Value == "[email protected]"
    string name = match.Groups[1]; // "xx"
    string domain = match.Groups[2]; // "yahoo.com.my"
}

Upvotes: 2

Dmitrii Dovgopolyi
Dmitrii Dovgopolyi

Reputation: 6301

Sting input = "contact [email protected] or [email protected] for more details";
String pattern = @"(\S*)@\S*\.\S*";
String result = Regex.Replace(input , pattern , "$1");

Upvotes: 0

Freelancer
Freelancer

Reputation: 9074

int end = myString.IndexOf('@');

string name=myString.Substring(0, end);

Try like this.

You can refer substring function here>>

http://www.dotnetperls.com/substring

Upvotes: 1

Related Questions