How to check if a string contains only letters and numbers using RegEx in C#

1 Answer

0 votes
using System;
using System.Text.RegularExpressions;

class Program
{
    static bool IsAlphanumeric(string str) {
        // Define the regular expression for alphanumeric characters
        string alphanumericPattern = "^[a-zA-Z0-9]+$";

        // Use Regex.IsMatch to check if the string matches the pattern
        return Regex.IsMatch(str, alphanumericPattern);
    }

    static void Main() {
        string str = "VuZ3q7J4wo35Pi";

        if (IsAlphanumeric(str)) {
            Console.WriteLine("The string contains only letters and numbers.");
        }
        else {
            Console.WriteLine("The string contains characters other than letters and numbers.");
        }
    }
}

 
/*
run:
     
The string contains only letters and numbers.
 
*/

 



answered Mar 25, 2025 by avibootz
...