I don't have much knowledge of regex, so please if you can help me, how to match this string:
a href="mailto:bristovski#moznosti.com.mk",
which is substring of other string.
Thanks.
Instead of using a regular expression to validate an email address, you can use the System.Net.Mail.MailAddress class. To determine whether an email address is valid, pass the email address to the MailAddress.MailAddress(String) class constructor.
public bool IsValid(string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
Or
string email = txtemail.Text;
Regex regex = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(emailaddress);
if (match.Success)
Response.Write(emailaddress + " is correct");
else
Response.Write(email + " is incorrect");
Related
I want to check whether email is valid or not .
Then check if it's personal email like gmail, yahoo etc.
I can do that with JavaScript but i want to do it in c# side
Can use MailAddress
var trimmedEmail = email.Trim();
if (string.IsNullOrEmpty(email) || trimmedEmail.EndsWith(".") )
return false;
try {
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == trimmedEmail;
}
catch {
return false;
}
OR
EmailAddressAttribute
var email = new EmailAddressAttribute();
email.IsValid(email);
If it is true then check it is personal or not by
string[] personalEmail = { "gmail","yahoo" };
string email = "xyz#yahoo.in";
var isPersonal= personalEmail.Any(x => email.Contains(x));
I have tried this code to validate multiple email addresses:
string email = "kamilar#recruit12.com; test#minh.com; test2#yahoo.com";
REGEX_EMAIL_ADDRESS_MULTI = #"^\s*([a-zA-Z0-9_%+~=$&*!#?\-\'](\.)?)*[a-zA-Z0-9_%+~=$&*!#?\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*((,|;)\s*([a-zA-Z0-9_%+~=$&*!#?\-\'](\.)?)*[a-zA-Z0-9_%+~=$&*!#?\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*)*$";
Regex reg = new Regex(REGEX_EMAIL_ADDRESS_MULTI);
var isOk = reg.IsMatch(email);
But it does not match - why?
Note that it matches with single address with this following expression:
#"^\s*([a-zA-Z0-9_%\-\'](\.)?)*[a-zA-Z0-9_%\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*$"
Any help?
UPDATED:
I do NOT want to split the string to validate one by one! That's why I need to ask on Stack Overflow!
As others have noted, you should be validating them one at a time.
string email = "kamilar#recruit12.com; test#minh.com; test2#yahoo.com";
string[] emailAddresses = email.Split(';').Select(x=>x.Trim()).ToArray();
string REGEX_EMAIL_ADDRESS_MULTI = #"^\s*([a-zA-Z0-9_%+~=$&*!#?\-\'](\.)?)*[a-zA-Z0-9_%+~=$&*!#?\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*((,|;)\s*([a-zA-Z0-9_%+~=$&*!#?\-\'](\.)?)*[a-zA-Z0-9_%+~=$&*!#?\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*)*$";
bool isOk = true;
foreach (string emailAddress in emailAddresses)
{
Regex reg = new Regex(REGEX_EMAIL_ADDRESS_MULTI);
if (!reg.IsMatch(email))
{
isOk = false;
break;
}
}
split the string at the ';'
string email = "kamilar#recruit12.com; test#minh.com; test2#yahoo.com";
string[] emails = email.Split(';');
then create a method that returns the validity
private bool CheckAddress(string address){
REGEX_EMAIL_ADDRESS_MULTI = #"^\s*([a-zA-Z0-9_%+~=$&*!#?\-\'](\.)?)*[a-zA-Z0-9_%+~=$&*!#?\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*((,|;)\s*([a-zA-Z0-9_%+~=$&*!#?\-\'](\.)?)*[a-zA-Z0-9_%+~=$&*!#?\-\']#([a-zA-Z0-9-](\.)?)+[a-zA-Z]{2,6}(\.[a-zA-Z]{2,6})+\s*)*$";
Regex reg = new Regex(REGEX_EMAIL_ADDRESS_MULTI);
return reg.IsMatch(email);
}
now just loop through the addresses
for(int i = 0; i > emails.Length; i++){
var isOK = CheckAddress(emails[i]);
}
This address is bad an invalidates the address string
These addresses are OK and the string is allowed
It is my fault as the first email address does not passed the single email regex test so the multiple email regex test should fail.
Thanks.
I am only capturing all valid email addresses from email body using below method.
public static IEnumerable<string> ParseAllEmailAddressess(string data)
{
HashSet<String> emailAddressess = new HashSet<string>();
Regex emailRegex = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
MatchCollection emailMatches = emailRegex.Matches(data);
foreach (Match emailMatch in emailMatches)
{
emailAddressess.Add(emailMatch.Value);
}
return emailAddressess;
}
The problem here is outlook converts the Signature image into some random email address something like (image001.png#01D36870.C9EE4D60) . And my method considering it as valid email address and captures it. I want to strip off such email address while parsing email body.
I can think of splitting the email address with . before # site and use the first index to match the image extension ".png" to identify valid email or not. But i think it not very efficient. Applying some reg ex to strip signature images content would be fast.
Any help would be appreciate.
I end up creating below method to strip the signature images email address from the email body.
public static readonly string[] _validExtensions = { "jpg", "bmp", "gif", "png", "jpeg","tiff","raw","psd" };
public static bool IsImageExtension(string email)
{
bool isContainsImageExt = false;
MailAddress addr = new MailAddress(email);
string username = addr.User;
if (!string.IsNullOrEmpty(username) && username.Contains('.'))
{
String[] parts = username.Split(new[] { '.' });
if(!string.IsNullOrEmpty(parts[0]) && !string.IsNullOrEmpty(parts[1]))
{
if(_validExtensions.Contains(parts[1].ToLower()) && (parts[0].ToLower().Contains("image")))
{
isContainsImageExt = true;
}
}
}
return isContainsImageExt;
}
I need to get the host from an email address string.
In .net 4.x I did this
var email1 = "test#test.com";
var email2 = "test2#yea.test.com"
var email1Host = new MailAddress(email1).Host;
var email2Host = new MailAddress(email2).Host;
email1Host prints "test.com"
email2Host prints "yea.test.com"
But now i need only the "test.com" part in both examples.
.Net Standard library 1.6 doesnt have the System.Net.Mail class so I can't do this anymore.
Whats another way of accomplishing the same thing in .net core but I only need the test.com part
I know there is a System.Net.Mail-netcore nuget package, but I really want to avoid installing a nuget just for this
Edit: Sorry for the confusion I forgot to mention that I only need the test.com
More examples were requested
#subdomain1.domain.co.uk => domain.co.uk
#subdomain1.subdomain2.domain.co.uk => domain.co.uk
#subdomain1.subdomain2.domain.com => domain.com
#domain.co.uk => domain.co.uk
#domain.com => domain.com
Using String Split and Regex,
var email1 = "test#test.com";
var email2 = "test2#yea.test.co.uk";
var email1Host = email1.Split('#')[1];
var email2Host = email2.Split('#')[1];
Regex regex = new Regex(#"[^.]*\.[^.]{2,3}(?:\.[^.]{2,3})?$");
Match match = regex.Match(email1Host);
if (match.Success)
{
Console.WriteLine("Email Host1: "+match.Value);
}
match = regex.Match(email2Host);
if (match.Success)
{
Console.WriteLine("Email Host2: "+match.Value);
}
Update: Using regex to get the Domain name
An alternative is to use the System.Uri class and prefix the email with 'mailto'.
class Program
{
static void Main(string[] args)
{
string email = "test#test.com";
string emailTwo = "test2#subdomain.host.com";
Uri uri = new Uri($"mailto:{email}");
Uri uriTwo = new Uri($"mailto:{emailTwo}");
string emailOneHost = uri.Host;
string emailTwoHost = uriTwo.Host;
Console.WriteLine(emailOneHost); // test.com
Console.WriteLine(emailTwoHost); // subdomain.host.com
Console.ReadKey();
}
}
Well, a bit of C# should do the trick:
string email = "test#test.com";
int indexOfAt = email.IndexOf('#');
//You do need to check the index is within the string
if (indexOfAt >= 0 && indexOfAt < email.Length - 1)
{
string host = email.Substring(indexOfAt + 1);
}
I am trying to use Regular Expression in C# Visual Studio 2013, I need to get a string that looks like this 192.168.1.254:65.
What I need to do is break this string into two values an IP Address and a Port number, Everything to the left of the colon is going to be the IP Address and Everything to the right of the colon is going to be the port, I need to do this with a regular expression in C# Code. So please place any namespaces that need to be added in the code to use the regular expression in C#, Example below
string mystring = "192.168.1.254:65";
string myipaddress = RegularExpressionMethod(ExpressionToGetIp, mystring);
string myportnumber = RegularExpressionMethod(ExpressionToGetPort, mystring);
This has nothing to do with IPEndPoints its a general abstraction method
Just use the .Split() method:
string mystring = "192.168.1.254:65";
string[] s = mystring.Split(':');
string ip = s[0]; // "192.168.1.254"
string port = s[1]; // "65"
If you need to double check the IP and Port numbers are in the right format, you can add the System.Net; namespace, then parse each string:
try
{
IPAddress IP = IPAddress.Parse(ip);
int PortNum = Int32.Parse(port);
}
catch
{
// catch any exceptions here
}
Or a simpler method might be (courtesy of EZI for reminding me) using the .TryParse() method. This is a bit easier to deal with, as this outputs a bool.
IPAddress IP;
int PortNum;
if (IPAddress.TryParse(s[0], out IP)) // If it is a valid IP
{ MessageBox.Show("IP address in correct format"); }
else { MessageBox.Show("IP address not in correct format"); }
if (Int32.TryParse(s[1], out PortNum)) // If it is a valid Port Number
{ MessageBox.Show("Port Number in correct format"); }
else { MessageBox.Show("Port Number not in correct format"); }
You could not reinvent the wheel and say something like this:
string myString = "192.168.1.254:65";
UriBuilder uri = new UriBuilder("http://" + myString );
string host = uri.Host ;
int port = uri.Port ;
You could simply say:
string[] parts = myString.Split(":");
string host = parts[0] ;
string port = parts[1] ;
But you should be aware that this will break if you get IPv6 address literals.
You could use a regular expression:
Regex rx = new Regex( #"^(?<host>.+):(?<port>\d+)$");
Match m = rx.Match(myString);
if ( !m.Success ) throw new FormatException() ;
string host = m.Groups["host"].Value ;
int port = int.Parse( m.Groups["port"].Value ) ;
Or you could get all fancy-like and write an extension method:
static class ExtensionMethods
{
public static DnsEndPoint ToDnsEndpoint( this string text)
{
Match m = rxDnsEndpoint.Match(text);
if ( !m.Success ) throw new FormatException("invalid endpoint format");
string host = m.Groups["host"].Value ;
int port = int.Parse( m.Groups["port"].Value ) ;
IPAddress address ;
bool parsed = IPAddress.TryParse( host , out address ) ;
AddressFamily family = parsed ? address.AddressFamily : AddressFamily.Unspecified ;
DnsEndPoint endpoint = new DnsEndPoint( host , port , family ) ;
return endpoint;
}
private static Regex rxDnsEndpoint = new Regex( #"^(?<host>.+):(?<port>\d+)$");
}
Which lets you say things like
DnsEndpoint endpoint = myString.ToDnsEndpoint() ;