EN
C# / .NET - check if string contains any letters
0
points
In this article, we would like to show you how to check if string contains any letters in C#.
Quick solution:
string text = "ABC";
string number = "123";
string regex = ".*[a-zA-Z].*";
var result1 = Regex.IsMatch(text, regex); // True
var result2 = Regex.IsMatch(number, regex); // False
or:
string text = "ABC";
string number = "123";
var result1 = text.All(Char.IsLetter); // True
var result2 = number.All(Char.IsLetter); // False
1. Practical example using regex
In this example, we use Regex.IsMatch() from System.Text.RegularExpressions namespace with specified regular expression to check if string contains any letters.
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string text = "ABC";
string number = "123";
string regex = ".*[a-zA-Z].*"; // regex to check if string contains any letters
bool result1 = Regex.IsMatch(text, regex);
bool result2 = Regex.IsMatch(number, regex);
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 with IsLetter() to check if all characters from the string are letters.
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string text = "ABC";
string number = "123";
bool result1 = text.All(Char.IsLetter);
bool result2 = number.All(Char.IsLetter);
Console.WriteLine(result1); // True
Console.WriteLine(result2); // False
}
}
Output:
True
False