First of all i would say i have seen many example here and googled but none found that matches all the condition i am looking for some match top 3 not below some inbetween.
public bool IsValidPhone(string Phone)
{
try
{
if (string.IsNullOrEmpty(Phone))
return false;
var r = new Regex(@"^\(?([0-9]{3})\)?[-.●]?([0-9]{3})[-.●]?([0-9]{4})$");
return r.IsMatch(Phone);
}
catch (Exception)
{
throw;
}
}
To extend upon FlyingStreudel's correct answer, I modified it to accept '.' as a delimiter, which was a requirement for me.
\(?\d{3}\)?[-\.]? *\d{3}[-\.]? *[-\.]?\d{4}
in use (finding all phone numbers in a string):
string text = "...the text to search...";
string pattern = @"\(?\d{3}\)?[-\.]? *\d{3}[-\.]? *[-\.]?\d{4}";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
Match match = regex.Match(text);
while (match.Success)
{
string phoneNumber = match.Groups[0].Value;
//TODO do something with the phone number
match = match.NextMatch();
}
for c#, the for US phone number validation should be like below
^\(?\d{3}?\)??-??\(?\d{3}?\)??-??\(?\d{4}?\)??-?$
777-777-7777
^?\(?\d{3}?\)??-??\(?\d{3}?\)??-??\(?\d{4}?\)??-?$
This allows:
\(?\d{3}\)?-? *\d{3}-? *-?\d{4}
Help yourself. Dont use a regex for this. Google release a great library to handle this specific use case: libphonenumber. There is an online demo of the lib.
public static void Main()
{
var phoneUtil = PhoneNumberUtil.GetInstance();
var numberProto = phoneUtil.Parse("(979) 778-0978", "US");
var formattedPhone = phoneUtil.Format(numberProto, PhoneNumberFormat.INTERNATIONAL);
Console.WriteLine(formattedPhone);
}
Demo on .NETFiddle