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:
xxxxxxxxxx
1
string number = "123";
2
string text = "ABC123";
3
4
string pattern = "^[0-9]+$"; // regular expression pattern
5
// to check if string contains only numbers
6
7
bool result1 = Regex.IsMatch(number, pattern); // True
8
bool result2 = Regex.IsMatch(text, pattern); // False
or:
xxxxxxxxxx
1
string number = "123";
2
string text = "A123";
3
4
bool result1 = number.All(Char.IsDigit); // True
5
bool result2 = text.All(Char.IsDigit); // False
In this example, we use regular expression with specified pattern
to check if string contains only numbers.
xxxxxxxxxx
1
using System;
2
using System.Text.RegularExpressions;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
string number = "123";
9
string text = "ABC123";
10
11
string pattern = "^[0-9]+$"; // regular expression pattern
12
// to check if string contains only numbers
13
14
bool result1 = Regex.IsMatch(number, pattern);
15
bool result2 = Regex.IsMatch(text, pattern);
16
17
Console.WriteLine(result1); // True
18
Console.WriteLine(result2); // False
19
}
20
}
Output:
xxxxxxxxxx
1
True
2
False
In this example, we use All()
method from System.Linq
namespace combined with Char.IsDigit()
to check if string contains only numbers.
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
string number = "123";
9
string text = "A123";
10
11
bool result1 = number.All(Char.IsDigit);
12
bool result2 = text.All(Char.IsDigit);
13
14
Console.WriteLine(result1); // True
15
Console.WriteLine(result2); // False
16
}
17
}
Output:
xxxxxxxxxx
1
True
2
False