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 myname@gmail.com

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


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.


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: myname@gmail.com

See also this answer for email parsing technique.

链接地址: http://www.djcxy.com/p/92852.html

上一篇: 电子邮件地址是否允许包含非

下一篇: 从URL中获取电子邮件地址,在c#中使用或不使用@的转义字符