Numbers only regex (digits only) C#

Numbers only (digits only)

Numbers only (or digits only) regular expressions can be used to validate if a string contains only numbers.

Basic numbers only regex

Below is a simple regular expression that allows validating if a given string contains only numbers:

new Regex("^\\d+$")

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Example code in C#:

using System.Text.RegularExpressions;
using System.Linq;
using System;
                    
public class Program
{
    public static void Main()
    {
        // Validate number
        Regex validateNumberRegex = new Regex("^\\d+$");
        Console.WriteLine(validateNumberRegex.IsMatch("42"));  // prints True
        
        // Extract number from a string
        Regex extractNumberrRegex = new Regex("\\d+");
        string [] extracted = extractNumberrRegex.Matches("Your message was viewed 203 times.")
            .Cast<Match>()
            .Select(m => m.Value) 
            .ToArray(); 
        Console.WriteLine(String.Join(",", extracted)); // prints 203
    }
}

Real number regex

Real number regex can be used to validate or exact real numbers from a string.

Pattern.compile("^(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)$")

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Example code in C#:

using System.Text.RegularExpressions;
using System.Linq;
using System;
                    
public class Program
{
    public static void Main()
    {
        // Validate real number
        Regex validateNumberRegex = new Regex("^(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)$");
        Console.WriteLine(validateNumberRegex.IsMatch("121220.22"));  // prints True
        
        // Extract real number from a string
        Regex extractNumberRegex = new Regex("(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)");
        string [] extracted = extractNumberRegex.Matches("Pi equals to 3.14")
            .Cast<Match>()
            .Select(m => m.Value) 
            .ToArray(); 
        Console.WriteLine(String.Join(",", extracted)); // prints 3.14
    }
}

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Notes on number only regex validation

In C# you can also validate number by trying to parse it:

int.TryParse("123");