445

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?

David Sopko
  • 5,263
  • 2
  • 38
  • 42
van
  • 9,159
  • 19
  • 60
  • 93

32 Answers32

727

\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.

Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • 13
    to support negative numbers you could use `Regex.Match(subjectString, @"-?\d+").Value` instead – Jon List Jun 10 '14 at 20:54
  • @JonList: OP stated in his comment above that he's not looking for negative numbers, but yes, that would be possible if desired. – Tim Pietzcker Jun 15 '14 at 13:02
  • 68
    This answer ist not complete (in C#). It is only getting the first number in the string. You have to itarate over the matches: resultString = string.Join(string.Empty, Regex.Matches(subjectString, @"\d+").OfType().Select(m => m.Value)); – Markus Jul 26 '14 at 04:53
  • 13
    @Markus: The question states "I need to extract ***a*** number contained within a string", and all the examples show a single number being present in the string. Iterating over a single item is not useful. – Tim Pietzcker Jul 26 '14 at 07:23
  • @Markus: For something like v2.0.1, your answer works (returns 201), whereas the above answer does not (returns just 2). It seems more complete to me. Thanks! – tclark333 Nov 05 '14 at 13:39
  • 1
    @TimPietzcker: hi, if I have sting like this "(14,347,198,538.033000)", how to get the value, what I should put instead of \d+ – Ayman Nov 19 '14 at 04:06
  • @TimPietzcker: "14347198538.033" , and is there any link you recommend to understand how RegularExpressions.Regex work? thanks – Ayman Nov 19 '14 at 07:16
  • 2
    @ayman: Oh, the commas are thousands separators? That will require a much more complex regex - which should be dealt with in a separate question. An excellent starting point is [Regular-Expressions.info](http://www.regular-expressions.info/) which also contains sections on .NET's regex engine. – Tim Pietzcker Nov 19 '14 at 18:26
  • 1
    simple, non regex answer: http://stackoverflow.com/questions/844461/return-only-digits-0-9-from-a-string/844479#844479 – mcfea Jun 16 '15 at 16:58
  • 1
    No this answer is WRONG. Can't believe all the upvotes. It doesn't work for phone numbers "(717) 555-1212" returns "717" – David Sopko Sep 09 '15 at 18:50
  • 3
    @DavidSopko: The question is about extracting a single integer number from a string, not about parsing phone numbers (there are enough questions about that topic on StackOverflow)... – Tim Pietzcker Sep 09 '15 at 18:54
  • @Tim Pietzcker if the answer is correct then the question is wrong because the SOLUTION is extract the FIRST number, and the QUESTION is 'extract numbers' <-- plural. You see in programming these seemingly slight differences in semantics have a major impact on the outcome. – David Sopko Sep 10 '15 at 20:08
  • 2
    @DavidSopko: "I have a requirement to find and extract *a number* contained within a string"... – Tim Pietzcker Sep 10 '15 at 20:42
  • 1
    Question changed to match the solution – David Sopko Sep 10 '15 at 21:28
  • 7
    @DavidSopko: What are you talking about? The original question asked for a way to extract a single number from a string, both in the title and in the question body. Subsequent edits to the question (a year after my answer and later) by people other than the original author changed the title to "numbers". If anything, that faulty edit should be rolled back. – Tim Pietzcker Sep 10 '15 at 21:39
  • This does not work if you try to parse a decimal or thousand separators. – Roger Far Jan 03 '21 at 19:17
278

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

string numericPhone = new String(phone.Where(Char.IsDigit).ToArray());
Dave
  • 3,273
  • 1
  • 17
  • 15
  • 3
    Nice solution for integers! Be aware that this won't work if you're trying to parse a decimal number because the decimal point is not a digit. – Elijah Lofgren May 11 '19 at 21:36
  • You can also replace the string construction with a `Concat` if you prefer: `string.Concat(phone.Where(Char.IsDigit).ToArray())`. – zcoop98 May 23 '23 at 19:56
103

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);
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Sasha Reminnyi
  • 3,442
  • 2
  • 23
  • 27
  • 26
    @Thomas: That code does not work, it results with `b == "System.Linq.Enumerable.."`. Correct (and even simpler) would be `b = String.Join("", a.Where(char.IsDigit))` – BlueRaja - Danny Pflughoeft May 29 '15 at 03:38
  • 1
    Good point, that'll teach me not to test the code I write in comment! You can also make a string from a char array using the `new string(char[])` constructor. – Thomas Jun 02 '15 at 08:32
  • 1
    Regex does a much better job. – Jason Kelley Aug 11 '15 at 20:31
  • @BlueRaja - Danny Pflughoeft Why not make your comment a proper answer so I can vote it up :-) – SteveC Aug 10 '16 at 10:37
  • 2
    NOTE: If the string contains multiple numbers, this answer will run them all together into a single number. E.g. "a12bcd345" results in "12345". (Which may be desirable or not, depending on the goal.) This is different than the top-voted Regex solution, which would return "12" for the case above. This matters for cases like phone numbers "555-111-2222". – ToolmakerSteve Oct 24 '17 at 17:53
  • this is a very cumbersome and low-level way and not recommended when you can use the built-in Regex support. – Gregor Nov 18 '20 at 18:10
47

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!");
}
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
41

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

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

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

// result: 7877636511
ejcortes
  • 609
  • 7
  • 13
26

Regex.Split can extract numbers from strings. You get all the numbers that are found in a string.

string input = "There are 4 numbers in this string: 40, 30, and 10.";
// Split on one or more non-digit characters.
string[] numbers = Regex.Split(input, @"\D+");
foreach (string value in numbers)
{
    if (!string.IsNullOrEmpty(value))
    {
    int i = int.Parse(value);
    Console.WriteLine("Number: {0}", i);
    }
}

Output:

Number: 4 Number: 40 Number: 30 Number: 10

Tabares
  • 4,083
  • 5
  • 40
  • 47
20

if the number has a decimal points, you can use below

using System;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
            Console.WriteLine(Regex.Match("anything 876.8 anything", @"\d+\.*\d*").Value);
            Console.WriteLine(Regex.Match("anything 876 anything", @"\d+\.*\d*").Value);
            Console.WriteLine(Regex.Match("$876435", @"\d+\.*\d*").Value);
            Console.WriteLine(Regex.Match("$876.435", @"\d+\.*\d*").Value);
        }
    }
}

results :

"anything 876.8 anything" ==> 876.8

"anything 876 anything" ==> 876

"$876435" ==> 876435

"$876.435" ==> 876.435

Sample : https://dotnetfiddle.net/IrtqVt

Community
  • 1
  • 1
Tarek El-Mallah
  • 4,015
  • 1
  • 31
  • 46
  • 1
    Thank you so much for this answer. I am using C# and VS2017 and was trying to figure out how do I find the value. Thank you again for your answer. – Bubbles Jan 10 '20 at 18:33
  • 1
    FYI this also extracts MULTIPLE values, perfect solution – WtFudgE Apr 06 '22 at 01:48
17

Here's a Linq version:

string s = "123iuow45ss";
var getNumbers = (from t in s
                  where char.IsDigit(t)
                  select t).ToArray();
Console.WriteLine(new string(getNumbers));
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
spajce
  • 7,044
  • 5
  • 29
  • 44
16

Another simple solution using Regex You should need to use this

using System.Text.RegularExpressions;

and the code is

string var = "Hello3453232wor705Ld";
string mystr = Regex.Replace(var, @"\d", "");
string mynumber = Regex.Replace(var, @"\D", "");
Console.WriteLine(mystr);
Console.WriteLine(mynumber);
13

You can also try this

string.Join(null,System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
BvdVen
  • 2,921
  • 23
  • 33
  • 1
    nice but if you have spaces between the numbers in the original string then it will give you 1 large concatenated string with both numbers joined (no space) – Mohammad Zekrallah Jun 17 '20 at 09:41
12

Here is another Linq approach which extracts the first number out of a string.

string input = "123 foo 456";
int result = 0;
bool success = int.TryParse(new string(input
                     .SkipWhile(x => !char.IsDigit(x))
                     .TakeWhile(x => char.IsDigit(x))
                     .ToArray()), out result);

Examples:

string input = "123 foo 456"; // 123
string input = "foo 456";     // 456
string input = "123 foo";     // 123
fubo
  • 44,811
  • 17
  • 103
  • 137
12
 string input = "Hello 20, I am 30 and he is 40";
 var numbers = Regex.Matches(input, @"\d+").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();
  • 1
    This is the best answer which gave me what I wanted, which is array of multiple numbers within string. If only it could ignore commas in numbers (thousand separator) then that would be perfect! :-) – Sagar Jun 13 '18 at 19:54
11

You can do this using String property like below:

 return new String(input.Where(Char.IsDigit).ToArray()); 

which gives only number from string.

Rahul Hendawe
  • 902
  • 1
  • 14
  • 39
Shyam sundar shah
  • 2,473
  • 1
  • 25
  • 40
11

Just use a RegEx to match the string, then convert:

Match match = Regex.Match(test , @"(\d+)");
if (match.Success) {
   return int.Parse(match.Groups[1].Value);
}
Daniel Gehriger
  • 7,339
  • 2
  • 34
  • 55
11

Here is another simple solution using Linq which extracts only the numeric values from a string.

var numbers = string.Concat(stringInput.Where(char.IsNumber));

Example:

var numbers = string.Concat("(787) 763-6511".Where(char.IsNumber));

Gives: "7877636511"

Bloggrammer
  • 921
  • 8
  • 21
9

For those who want decimal number from a string with Regex in TWO line:

decimal result = 0;
decimal.TryParse(Regex.Match(s, @"\d+").Value, out result);

Same thing applys to float, long, etc...

Richard Fu
  • 616
  • 10
  • 27
8
var match=Regex.Match(@"a99b",@"\d+");
if(match.Success)
{
    int val;
    if(int.TryParse(match.Value,out val))
    {
        //val is set
    }
}
spender
  • 117,338
  • 33
  • 229
  • 351
7

The question doesn't explicitly state that you just want the characters 0 to 9 but it wouldn't be a stretch to believe that is true from your example set and comments. So here is the code that does that.

        string digitsOnly = String.Empty;
        foreach (char c in s)
        {
            // Do not use IsDigit as it will include more than the characters 0 through to 9
            if (c >= '0' && c <= '9') digitsOnly += c;
        }

Why you don't want to use Char.IsDigit() - Numbers include characters such as fractions, subscripts, superscripts, Roman numerals, currency numerators, encircled numbers, and script-specific digits.

Atters
  • 801
  • 8
  • 19
6
var outputString = String.Join("", inputString.Where(Char.IsDigit));

Get all numbers in the string. So if you use for examaple '1 plus 2' it will get '12'.

Tom
  • 139
  • 1
  • 14
5

Extension method to get all positive numbers contained in a string:

    public static List<long> Numbers(this string str)
    {
        var nums = new List<long>();
        var start = -1;
        for (int i = 0; i < str.Length; i++)
        {
            if (start < 0 && Char.IsDigit(str[i]))
            {
                start = i;
            }
            else if (start >= 0 && !Char.IsDigit(str[i]))
            {
                nums.Add(long.Parse(str.Substring(start, i - start)));
                start = -1;
            }
        }
        if (start >= 0)
            nums.Add(long.Parse(str.Substring(start, str.Length - start)));
        return nums;
    }

If you want negative numbers as well simply modify this code to handle the minus sign (-)

Given this input:

"I was born in 1989, 27 years ago from now (2016)"

The resulting numbers list will be:

[1989, 27, 2016]
Thomas C. G. de Vilhena
  • 13,819
  • 3
  • 50
  • 44
5

An interesting approach is provided here by Ahmad Mageed, uses Regex and StringBuilder to extract the integers in the order in which they appear in the string.

An example using Regex.Split based on the post by Ahmad Mageed is as follows:

var dateText = "MARCH-14-Tue";
string splitPattern = @"[^\d]";
string[] result = Regex.Split(dateText, splitPattern);
var finalresult = string.Join("", result.Where(e => !String.IsNullOrEmpty(e)));
int DayDateInt = 0;

int.TryParse(finalresult, out DayDateInt);
d219
  • 2,707
  • 5
  • 31
  • 36
Simba
  • 489
  • 6
  • 7
5

I have used this one-liner to pull all numbers from any string.

var phoneNumber = "(555)123-4567";
var numsOnly = string.Join("", new Regex("[0-9]").Matches(phoneNumber)); // 5551234567
Reed
  • 1,515
  • 1
  • 21
  • 38
  • Strangely for me var resolves to a string with the following content "System.Text.RegularExpressions.MatchCollection" Maybe adifferent C# version ? – Jindil Jul 07 '22 at 08:38
  • could also use @"\d+" for the regex. Note you'll need the @ in front to allow the use of the \ – sirclesam Jan 14 '23 at 05:05
  • 1
    @sirclesam Yep totally, I just default to `[0-9]` because its more readable in my opinion. But that's totally just flavor! – Reed Jan 14 '23 at 18:36
3

Did the reverse of one of the answers to this question: How to remove numbers from string using Regex.Replace?

// Pull out only the numbers from the string using LINQ

var numbersFromString = new String(input.Where(x => x >= '0' && x <= '9').ToArray());

var numericVal = Int32.Parse(numbersFromString);
Community
  • 1
  • 1
mwilly
  • 31
  • 1
3
  string verificationCode ="dmdsnjds5344gfgk65585";
            string code = "";
            Regex r1 = new Regex("\\d+");
          Match m1 = r1.Match(verificationCode);
           while (m1.Success)
            {
                code += m1.Value;
                m1 = m1.NextMatch();
            }
2

Here is my Algorithm

    //Fast, C Language friendly
    public static int GetNumber(string Text)
    {
        int val = 0;
        for(int i = 0; i < Text.Length; i++)
        {
            char c = Text[i];
            if (c >= '0' && c <= '9')
            {
                val *= 10;
                //(ASCII code reference)
                val += c - 48;
            }
        }
        return val;
    }
HS_Kernel
  • 21
  • 5
1
static string GetdigitFromString(string str)
    {
        char[] refArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
        char[] inputArray = str.ToCharArray();
        string ext = string.Empty;
        foreach (char item in inputArray)
        {
            if (refArray.Contains(item))
            {
                ext += item.ToString();
            }
        }
        return ext;
    }
1

here is my solution

string var = "Hello345wor705Ld";
string alpha = string.Empty;
string numer = string.Empty;
foreach (char str in var)
{
    if (char.IsDigit(str))
        numer += str.ToString();
    else
        alpha += str.ToString();
}
Console.WriteLine("String is: " + alpha);
Console.WriteLine("Numeric character is: " + numer);
Console.Read();
0
string s = "kg g L000145.50\r\n";
        char theCharacter = '.';
        var getNumbers = (from t in s
                          where char.IsDigit(t) || t.Equals(theCharacter)
                          select t).ToArray();
        var _str = string.Empty;
        foreach (var item in getNumbers)
        {
            _str += item.ToString();
        }
        double _dou = Convert.ToDouble(_str);
        MessageBox.Show(_dou.ToString("#,##0.00"));
0

You will have to use Regex as \d+

\d matches digits in the given string.

Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103
0

Using @tim-pietzcker answer from above, the following will work for PowerShell.

PS C:\> $str = '1 test'
PS C:\> [regex]::match($str,'\d+').value
1
user2320464
  • 359
  • 1
  • 5
  • 11
0

Using StringBuilder is slightly more performent than string concatanation in a loop. If you are dealing with large strings, it is considerably more performant.

    public static string getOnlyNumbers(string input)
    {
        StringBuilder stringBuilder = new StringBuilder(input.Length);
        for (int i = 0; i < input.Length; i++)
            if (input[i] >= '0' && input[i] <= '9')
                stringBuilder.Append(input[i]);

        return stringBuilder.ToString();
    }

Note: above example function only works for positive numbers

t.m.
  • 1,430
  • 16
  • 29
-3

Based on the last sample I created a method:

private string GetNumberFromString(string sLongString, int iLimitNumbers)
{
    string sReturn = "NA";
    int iNumbersCounter = 0;
    int iCharCounter = 0; 

    string sAlphaChars = string.Empty;
    string sNumbers = string.Empty;
    foreach (char str in sLongString)
    {
        if (char.IsDigit(str))
        {
            sNumbers += str.ToString();
            iNumbersCounter++;
            if (iNumbersCounter == iLimitNumbers)
            {
                return sReturn = sNumbers;
            }
        }
        else
        {
            sAlphaChars += str.ToString();
            iCharCounter++;
            // reset the counter 
            iNumbersCounter = 0; 
        }
    }
    return sReturn;
}
bobble bubble
  • 16,888
  • 3
  • 27
  • 46
MrJTNY
  • 1
  • 2