EN
C# / .NET - check if string contains any numbers
0 points
In this article, we would like to show you how to check if string contains any numbers in C#.
Quick solution:
xxxxxxxxxx
1
string text1 = "ABC123";
2
string text2 = "ABCDEF";
3
4
string pattern = "\\d"; // regular expression pattern
5
// to check if string contains any numbers
6
7
bool result1 = Regex.IsMatch(text1, regex); // True
8
bool result2 = Regex.IsMatch(text2, regex); // False
or:
xxxxxxxxxx
1
string text1 = "ABC123";
2
string text2 = "ABCDEF";
3
4
bool result1 = text1.Any(Char.IsDigit); // True
5
bool result2 = text2.Any(Char.IsDigit); // False
In this example, we use regular expression with specified pattern
to check if string contains any numbers (\d
stands for digits).
xxxxxxxxxx
1
using System;
2
using System.Text.RegularExpressions;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
string text1 = "ABC123";
9
string text2 = "ABCDEF";
10
11
string pattern = "\\d"; // regular expression pattern to check if string contains any numbers
12
13
bool result1 = Regex.IsMatch(text1, pattern);
14
bool result2 = Regex.IsMatch(text2, pattern);
15
16
Console.WriteLine(result1); // True
17
Console.WriteLine(result2); // False
18
}
19
}
Output:
xxxxxxxxxx
1
True
2
False
In this example, we use Any()
method from System.Linq
namespace combined with Char.IsDigit()
to check if string contains numbers.
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
string text1 = "ABC123";
9
string text2 = "ABCDEF";
10
11
bool result1 = text1.Any(Char.IsDigit);
12
bool result2 = text2.Any(Char.IsDigit);
13
14
Console.WriteLine(result1); // True
15
Console.WriteLine(result2); // False
16
}
17
}
Output:
xxxxxxxxxx
1
True
2
False