Languages
[Edit]
EN

C# / .NET - check if string contains any letters

0 points
Created by:
Trenton-McKinney
618

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

References

  1. Regex.IsMatch Method (System.Text.RegularExpressions) | Microsoft Docs
  2. Enumerable.All<TSource>() Method (System.Linq) | Microsoft Docs
  3. Char.IsLetter Method (System) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join