Aju Mon
Aju Mon

Reputation: 235

Get email address from the url with and without escape character of @ in c#

I have a Url as shown below

http://www.mytestsite.com/TesPage.aspx?pageid=32&LangType=1033&emailAddress=myname%40gmail.com

I would like to have the email address from the url

Note

The email address may have the escape character of @ sometimes.

ie it may be myname%40gmail.com or [email protected]

Is there any way to get the email address from a url, such that if the that have the matching regx for an email patten and retrieve the value.

Here is the code that i have tried

string theRealURL = "http://www.mytestsite.com/TesPage.aspx?pageid=32&LangType=1033&emailAddress=myname%40gmail.com";

string emailPattern = @"^([\w\.\-]+)(((%40))|(@))([\w\-]+)((\.(\w){2,3})+)$";
  Match match = Regex.Match(theRealURL, emailPattern);
  if (match.Success)
     string campaignEmail = match.Value;

If anyone helps what went wrong here?

Thanks

Upvotes: 0

Views: 1628

Answers (2)

Rawling
Rawling

Reputation: 50144

If possible, don't use a regular expression when there are domain-specific tools available.

Unless there is a reason not to reference System.Web, use

var uri = new Uri(
    "http://www.mytestsite.com/TesPage.aspx?pageid=32&LangType=1033&emailAddress=myname%40gmail.com");
var email = HttpUtility.ParseQueryString(uri.Query).Get("emailAddress");

Edit: If (for some reason) you don't know the name of the parameter containing the address, use appropriate tools to get all the query values and then see what looks like an email address.

var emails = query
    .AllKeys
    .Select(k => query[k])
    .Where(v => Regex.IsMatch(v, emailPattern));

If you want to improve your email regex too, there are plenty of answers about that already.

Upvotes: 4

dav_i
dav_i

Reputation: 28127

Starting with Rawling's answer in response to the comment

The query string parameter can vary.. How can it possible without using the query string parameter name.

The follwing code will produce a list (emails) of the emails in the supplied input:

var input = "http://www.mytestsite.com/TesPage.aspx?pageid=32&LangType=1033&emailAddress=myname%40gmail.com";
var queryString = new Uri(input).Query;

var parsed = HttpUtility.ParseQueryString(queryString);

var attribute = new EmailAddressAttribute();

var emails = new List<string>();
foreach (var key in parsed.Cast<string>())
{
    var value = parsed.Get(key);
    if (attribute.IsValid(value))
        emails.Add(value);
}

Console.WriteLine(String.Join(", ", emails)); // prints: [email protected]

See also this answer for email parsing technique.

Upvotes: 0

Related Questions