Languages
[Edit]
EN

C# / .NET - check if string contains only numbers

0 points
Created by:
Theodora-Battle
528

In this article, we would like to show you how to check if string contains only numbers in C#.

Quick solution:

string number = "123";
string text = "ABC123";

string pattern = "^[0-9]+$"; // regular expression pattern
                             // to check if string contains only numbers

bool result1 = Regex.IsMatch(number, pattern); // True
bool result2 = Regex.IsMatch(text, pattern);   // False

or:

string number = "123";
string text = "A123";

bool result1 = number.All(Char.IsDigit); // True
bool result2 = text.All(Char.IsDigit);   // False

 

Practical example

In this example, we use regular expression with specified pattern to check if string contains only numbers.

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string number = "123";
        string text = "ABC123";

        string pattern = "^[0-9]+$"; // regular expression pattern
                                     // to check if string contains only numbers

        bool result1 = Regex.IsMatch(number, pattern);
        bool result2 = Regex.IsMatch(text, pattern);

        Console.WriteLine(result1); // True
        Console.WriteLine(result2); // False
    }
}

Output:

True
False

2. Using System.Linq

In this example, we use All() method from System.Linq namespace combined with Char.IsDigit() to check if string contains only numbers.

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        string number = "123";
        string text = "A123";

        bool result1 = number.All(Char.IsDigit);
        bool result2 = text.All(Char.IsDigit);

        Console.WriteLine(result1); // True
        Console.WriteLine(result2); // False
    }
}

Output:

True
False

References

  1. Regex.IsMatch Method (System.Text.RegularExpressions) | Microsoft Docs
  2. Enumerable.All Method (System.Linq) | Microsoft Docs
  3. Char.IsDigit Method (System) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join