EN
C# / .NET - check if string contains only numbers
0
points
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