Find Numbers In A C# String

Written by Khalid Abuhakmeh
2
This post is days old.

Data can often be messy and cleaning it up falls on the shoulders of you, the developer. It’s also easy to search StackOverflow for complex regular expression solutions. In this post I’ll show you an easy one liner to get all numbers from a string.

Let’s start with the value.

var value = "hello world 12345";

As you can see, it has a mix of alpha and numeric characters. What we want, is a string that only contains the digits 12345.

Let’s use some LINQ!

var result = string.Concat(value.Where(Char.IsDigit));

The resulting output is:

"12345"

The full solution being is below.

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var value = "hello 12345";
        var result = string.Concat(value.Where(Char.IsDigit));
        Console.WriteLine(result);
    }
}

Try it out on DotNetFiddle. This will perform better than a RegEx solution. Hope you found it helpful :)

Suggested reading

Comments