Loading ...

Regex: Allow alphanumeric characters only | CodeAsp.Net

Regex: Allow alphanumeric characters only

 /5
0 (0votes)

In this blog I will show how to validate a string to allow alphanumeric characters only in a string with REGEX. Below is the sample code to do the same:

using System;
using System.Text.RegularExpressions;

namespace SampleConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Regex regex = new Regex("^[a-zA-Z0-9]*$");


            //First test
            const string inputString1 = "abc";
            Console.WriteLine(regex.IsMatch(inputString1)
                ? "Matched" : "Not matched");

            //Second test
            const string inputString2 = "abc123";
            Console.WriteLine(regex.IsMatch(inputString2)
                ? "Matched" : "Not matched");

            //Third test
            const string inputString3 = "abc_)@#$";
            Console.WriteLine(regex.IsMatch(inputString3)
                ? "Matched" : "Not matched");

           
            Console.ReadLine();
        }
    }
}

Output:

Below is the explanation of regex:

^[a-zA-Z0-9]*$

Assert position at the beginning of the string «^»
Match a single character present in the list below «[a-zA-Z0-9]*»
   Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
   A character in the range between “a” and “z” «a-z»
   A character in the range between “A” and “Z” «A-Z»
   A character in the range between “0” and “9” «0-9»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»


Created with RegexBuddy

Comments (no comments yet)

Top Posts