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:
xxxxxxxxxx
1
string text1 = "ABC";
2
string text2 = "ABC123";
3
4
string regex = "^[a-zA-Z]+$";
5
6
bool result1 = Regex.IsMatch(text1, regex); // True
7
bool result2 = Regex.IsMatch(text2, regex); // False
or:
xxxxxxxxxx
1
string text1 = "ABC";
2
string text2 = "ABC123";
3
4
bool result1 = text1.All(Char.IsLetter); // True
5
bool result2 = text2.All(Char.IsLetter); // False
In this example, we use a regular expression (regex) with IsMatch()
to check if the strings contain only letters.
xxxxxxxxxx
1
using System;
2
using System.Text.RegularExpressions;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
string text1 = "ABC";
9
string text2 = "ABC123";
10
11
string regex = "^[a-zA-Z]+$";
12
13
bool result1 = Regex.IsMatch(text1, regex);
14
bool result2 = Regex.IsMatch(text2, regex);
15
16
Console.WriteLine(result1); // True
17
Console.WriteLine(result2); // False
18
}
19
}
Output:
xxxxxxxxxx
1
True
2
False
In this example, we use All()
from System.Linq
with IsLetter()
method to check if all characters in strings are letters.
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
string text1 = "ABC";
9
string text2 = "ABC123";
10
11
bool result1 = text1.All(Char.IsLetter);
12
bool result2 = text2.All(Char.IsLetter);
13
14
Console.WriteLine(result1); // True
15
Console.WriteLine(result2); // False
16
}
17
}
Output:
xxxxxxxxxx
1
True
2
False