Using c# regex matches to check if string is alphnumeric

The c# regex.match method is typically used to validate a string or to ensure that a string conforms to a particular pattern without retrieving that string for subsequent manipulation.Below is a string extension method that uses c# regex matches to check if the string is alphanumeric.It will return true if given string contain only number and alphabets.

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
    
    public static class CheckString
    {
        public static bool IsAlphanumeric(string source)
        {
            Regex pattern = new Regex("[^0-9a-zA-Z]");
            return !pattern.IsMatch(source);
        }
    }
    
    // THE Below Example USe Code.
    
    class Program
    {
        static void Main(string[] args)
        {
            string testString = Console.ReadLine();

            if (CheckString.IsAlphanumeric(testString))
                Console.WriteLine("Yes string is Alphanumeric!");
            else
                Console.WriteLine("No string is not Alphanumeric!");
   
            Console.ReadKey();
        }
     }



Tags: , , , ,

Join Us!