Nate Pet Nate Pet - 1 year ago 154
C# Question

C# Regex Phone Number Check

I have the following to check if the phone number is in the following format
(XXX) XXX-XXXX. The below code always return true. Not sure why.

Match match = Regex.Match(input, @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}");

// Below code always return true
if (match.Success) { ....}

Answer Source

It doesn't always match, but it will match any string that contains three digits, followed by a hyphen, followed by four more digits. It will also match if there's something that looks like an area code on the front of that. So this is valid according to your regex:


To validate that the string contains a phone number and nothing else, you need to add anchors at the beginning and end of the regex:

@"^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download