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. Kindly let me know how to put all of them in one place.
(xxx)xxxxxxx
(xxx) xxxxxxx
(xxx)xxx-xxxx
(xxx) xxx-xxxx
xxxxxxxxxx
xxx-xxx-xxxxx
Using as :
const string MatchPhonePattern =
@"\(?\d{3}\)?-? *\d{3}-? *-?\d{4}";
Regex rx = new Regex(MatchPhonePattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Find matches.
MatchCollection matches = rx.Matches(text);
// Report the number of matches found.
int noOfMatches = matches.Count;
// Report on each match.
foreach (Match match in matches)
{
tempPhoneNumbers= match.Value.ToString(); ;
}
SAMPLE OUTPUT:
3087774825
(281)388-0388
(281)388-0300
(979) 778-0978
(281)934-2479
(281)934-2447
(979)826-3273
(979)826-3255
1334714149
(281)356-2530
(281)356-5264
(936)825-2081
(832)595-9500
(832)595-9501
281-342-2452
1334431660
To add to all of the above suggestions, here's my RegEx that will enforce NANP standards:
This regular expression enforces NANP Standard rules such as
N11 codes are used to provide three-digit dialing access to special services
, and thus excludes them using a conditional capture. It also accounts for up to 3 non-digit characters (\D{0,3}
) in between sections, because I've seen some funky data.From the provided testing data, here's the Output:
Note that there were two sample values omitted due to not being valid phone numbers by NANP Standards: Area Code begins with 1
The rule I am referring to can be found on the National NANPA's website's Area Codes page stating,
The format of an area code is NXX, where N is any digit 2 through 9 and X is any digit 0 through 9.
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):
\(?\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.
Demo on .NETFiddle