EN
C# / .NET - check if string contains only letters
0
points
In this article, we would like to show you how to check if string contains only letters in C#.
Quick solution:
string text1 = "ABC";
string text2 = "ABC123";
string regex = "^[a-zA-Z]+$";
bool result1 = Regex.IsMatch(text1, regex); // True
bool result2 = Regex.IsMatch(text2, regex); // False
or:
string text1 = "ABC";
string text2 = "ABC123";
bool result1 = text1.All(Char.IsLetter); // True
bool result2 = text2.All(Char.IsLetter); // False
1. Practical example using regex
In this example, we use a regular expression (regex) with IsMatch() to check if the strings contain only letters.
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string text1 = "ABC";
string text2 = "ABC123";
string regex = "^[a-zA-Z]+$";
bool result1 = Regex.IsMatch(text1, regex);
bool result2 = Regex.IsMatch(text2, regex);
Console.WriteLine(result1); // True
Console.WriteLine(result2); // False
}
}
Output:
True
False
2. Using All() with IsLetter() method
In this example, we use All() from System.Linq with IsLetter() method to check if all characters in strings are letters.
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string text1 = "ABC";
string text2 = "ABC123";
bool result1 = text1.All(Char.IsLetter);
bool result2 = text2.All(Char.IsLetter);
Console.WriteLine(result1); // True
Console.WriteLine(result2); // False
}
}
Output:
True
False