Extract number from string?

Say I have a string such as "20 Boxes" and I want to extract the number from that string as an integer to carry out some calculations on it. How should I go about this?

I'm used to using parseInt, but in Unity (unlike in JS) that won't accept any string that contains letters, so that's out unless I split the string up first. If I do have to split the string up first, what's the most efficient way to do so?


You can also use Regex.Replace. This Regex find/replace pattern will remove all non-numbers from a given string.

If you're already familiar with Regex, just use this pattern:


Which selects all non-numbered characters. Then, just replace with an empty string ("").

If you aren't familiar with Regex, this code should do it for you:

string numbersOnly = Regex.Replace("20 Boxes", "[^0-9]", "");

Remember to add the Using directive for the .NET Regex class:

using System.Text.RegularExpressions;

I would also like to point out, before all the Webplayer-lovers hound me for it, that the RegularExpressions library adds about 900k to the web player download, so if this is unacceptable for you, don't use Regex. ;)

You can use the String.Split method. Combine that with int.TryParse should get you what you want.

string sentence = “10 cats, 20 dogs, 40 fish and 1 programmer.”;

string[] digits= Regex.Split(sentence, @"\D+");
            foreach (string value in digits)
                int number;
                if (int.TryParse(value, out number))


Since I was in need of something similar adding this solution for future reference!