Check String for alphanumeric in C#

In this article we will discuss about whether the string is alphanumeric or not in C# using regular expression.
  • 11078

To check whether the string is alphanumeric or not we will use the regular expressions in C#. The regex class is contained in System.Text.RegularExpressions namespace. Here IsMatch() method has been used which returns a boolean result if the supplied regular expression matches within the string.

Lets have a look on the following lines:

if (System.Text.RegularExpressions.Regex.IsMatch(str, @"^[a-zA-Z0-9]+$"))

sb.AppendLine("Example \"" + str + "\" is an alphanumeric string.");

else

sb.AppendLine("Example \"" + str + "\" is NOT an alphanumeric string.");

In this above code we have used [] brackets if we are to give range values such as 0 - 9 or a-z or A-Z. Here in the IsMatch() method two parameters have been supplied first is string name which will be match with the regular expression specified and second is regular expression with which the string will be matched. If this the string will be matched with this regular expression then IsMatch() method will return true value otherwise false value.

Here is the complete program in C#

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace ConsoleApplication8

{

    class Program

    {

        static void Main(string[] args)

        {

            string str1 = "xyz123";

            string str2 = "xyz&123";

 

            string[] array = { str1, str2 };

            StringBuilder sb = new StringBuilder();

            foreach (string str in array)

            {

                if (System.Text.RegularExpressions.Regex.IsMatch(str, @"^[a-zA-Z0-9]+$"))

                    sb.AppendLine("Example \"" + str + "\" is an alphanumeric string.");

                else

                    sb.AppendLine("Example \"" + str + "\" is NOT an alphanumeric string.");

            }

            Console.WriteLine(sb);

            Console.ReadLine();

        }

    }

}


Further Readings
 
You may also want to read these related articles.

Ask Your Question  

Got a programming related question? You may want to post your question here

Categories

More Articles

© 2018 DotNetHeaven. All rights reserved.