Checking C # Regex Phone Number

I have the following to check if the phone number is in the following format (XXX) XXX-XXXX. The code below always returns true. I do not know why.

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

    // Below code always return true
    if (match.Success) { ....}
+5
source share
5 answers

It does not always match, but it will match any line containing three digits, followed by a hyphen, and then four more digits. It will also match if there is something similar to the area code on the front. So this is true according to your regex:

%%%%%%%%%%%%%%(999)123-4567%%%%%%%%%%%%%%%%%

To confirm that the line contains a phone number and nothing else, you need to add anchors to the beginning and end of the regular expression:

@"^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$"
+8

, , .

, ?

, .

( # ), Regex IgnorePatternWhitespace, . , # .

string pattern = @"
^                  # From Beginning of line
(?:\(?)            # Match but don't capture optional (
(?<AreaCode>\d{3}) # 3 digit area code
(?:[\).\s]?)       # Optional ) or . or space
(?<Prefix>\d{3})   # Prefix
(?:[-\.\s]?)       # optional - or . or space
(?<Suffix>\d{4})   # Suffix
(?!\d)             # Fail if eleventh number found";

10 , ( -, , .. :

(555)555-5555 (OK)
5555555555 (ok)
555 555 5555(ok)
555.555.5555 (ok)
55555555556 (not ok - match failure - too many digits)
123.456.789 (failure)

IgnorePatternWhitespace:

^(?:\(?)(?<AreaCode>\d{3})(?:[\).\s]?)(?<Prefix>\d{3})(?:[-\.\s]?)(?<Suffix>\d{4})(?!\d)

, Named Captures

^(?:\(?)(\d{3})(?:[\).\s]?)(\d{3})(?:[-\.\s]?)(\d{4})(?!\d)

, ExplicitCapture

^\(?(?<AreaCode>\d{3})[\).\s]?(?<Prefix>\d{3})[-\.\s](?<Suffix>\d{4})(?!\d)
+11

, exp. +1

"(XXX) XXX-XXXX" ,

@"^\(\d{3}\) \d{3}-\d{4}$"
+6

#, . . : 0123456789, 012-345-6789, (012) -345-6789, (012) 3456789 012 3456789, 012 345 6789, 012 345-6789, (012) 345-6789, 012.345.6789

List<string> phoneList = new List<string>();
Regex rg = new Regex(@"\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})");
MatchCollection m = rg.Matches(html);
foreach (Match g in m)
{
    if (g.Groups[0].Value.Length > 0)
        phoneList.Add(g.Groups[0].Value);
}
+4

, +33 6 87 17 00 11 ( , ). : 1. , , "+" 2. + . ( , ). , +1 , , .

+1

All Articles