Find and extract a number from a string

673,657

Solution 1

go through the string and use Char.IsDigit

string a = "str123";
string b = string.Empty;
int val;

for (int i=0; i< a.Length; i++)
{
    if (Char.IsDigit(a[i]))
        b += a[i];
}

if (b.Length>0)
    val = int.Parse(b);

Solution 2

\d+ is the regex for an integer number. So

//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, @"\d+").Value;

returns a string containing the first occurrence of a number in subjectString.

Int32.Parse(resultString) will then give you the number.

Solution 3

Here's how I cleanse phone numbers to get the digits only:

string numericPhone = new String(phone.Where(Char.IsDigit).ToArray());

Solution 4

use regular expression ...

Regex re = new Regex(@"\d+");
Match m = re.Match("test 66");

if (m.Success)
{
    Console.WriteLine(string.Format("RegEx found " + m.Value + " at position " + m.Index.ToString()));
}
else
{
    Console.WriteLine("You didn't enter a string containing a number!");
}

Solution 5

What I use to get Phone Numbers without any punctuation...

var phone = "(787) 763-6511";

string.Join("", phone.ToCharArray().Where(Char.IsDigit));

// result: 7877636511
Share:
673,657
van
Author by

van

Updated on July 08, 2022

Comments

  • van
    van almost 2 years

    I have a requirement to find and extract a number contained within a string.

    For example, from these strings:

    string test = "1 test"
    string test1 = " 1 test"
    string test2 = "test 99"
    

    How can I do this?