Sanjiv Rajput Sanjiv Rajput -4 years ago 50
C# Question

How to extract contact numbers from long description field?

This is my long input string which contains contact number in between this string like below:


sgsdgsdgs 123-456-7890 sdgsdgs (123) 456-7890 sdgsdgsdg 123 456 7890
sdgsdgsdg 123.456.7890 sdfsdfsdfs +91 (123) 456-7890


Now i want to Extract all input numbers like:

123-456-7890
(123) 456-7890
123 456 7890
123.456.7890
+91 (123) 456-7890


I want to store all this number in array.

This is what i have tried but getting only 2 numbers only:

string pattern = @"^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$";
Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);

var a = txt.Split();
List < string > list = new List < string > ();
foreach(var item in a) {
if (reg.IsMatch(item)) {
list.Add(item);
}
}


Can anybody help me with this??

Answer Source

Try to use regex directly on a String, like:

using System.IO;
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Regex regex = new Regex(@"\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*");
        Match match = regex.Match("sgsdgsdgs 123-456-7890 sdgsdgs (123) 456-7890 sdgsdgsdg 123 456 7890 sdgsdgsdg 123.456.7890 sdfsdfsdfs +91 (123) 456-7890");
        List < string > list = new List < string > ();
        while (match.Success)
        {
            list.Add(match.Value);
            match = match.NextMatch();
        }
        list.ForEach(Console.WriteLine);
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download