How to make a Regex pattern in C # with the character '@'?

0

Good, I want to make a Pattern Regex to verify that in a chain there is the arroba character in the middle of two text strings in C #, the conventional:

[email protected].

if (Regex.IsMatch(email, "\@{1,1}")) {  
    //Codigo  
}  

In the previous code I tried to verify that the character was at least and maximum once in the chain, but I guess that \ @ is not the regex corrector to reference that character for a Regex.

    
asked by Parzival 28.09.2017 в 15:32
source

2 answers

2

As you have already answered it is not necessary to escape the @ sign, so a valid solution would be:

Regex.IsMatch(email, "[a-zA-Z]" + "@" + "[a-zA-Z"))

If you want to validate an email address, you'd better use the following Regex:

@"^[\w!#$%&'*+\-/=?\^_'{|}~]+(\.[\w!#$%&'*+\-/=?\^_'{|}~]+)*" + "@"+ @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$";

The MailAddress class does not detect all cases (eg: abc. @ def.com or abc..123 @ def.com).

Here you can find more Regex (in English).

    
answered by 28.09.2017 / 16:03
source
3

Actually, you have the inverted bar. You do not need to escape the @ in regular .NET expressions since it is not a special character.

You can find many examples of regular expressions on the internet to validate the format of an email. Although you can also use the constructor of the class MailAddress to check if a string has a valid email format:

public bool IsValid(string emailaddress)
{
    try
    {
        MailAddress m = new MailAddress(emailaddress);

        return true;
    }
    catch (FormatException)
    {
        return false;
    }
}
    
answered by 28.09.2017 в 15:54