Loading ...

Regex: Remove all non alpha numeric characters from a string | CodeAsp.Net

Regex: Remove all non alpha numeric characters from a string

 /5
0 (0votes)

In this blog I will show how to remove all non alpha numeric characters from a string with REGEX. Let's say we have a string "Hello!@#$123456789~~-_user456welcome" and  remove all non alpha numeric characters so that the string looks like "Hello123456789user456welcome". Below is the sample code to do the same:

using System;
using System.Text.RegularExpressions;

namespace SampleConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            const string inputString = @"Hello!@#$123456789~~-_user456welcome";

            Regex regx = new Regex("[^a-zA-Z0-9]");
            string output = regx.Replace(inputString, "");

            Console.WriteLine(output);
            Console.ReadLine();
        }
    }
}

Output:

Below is the explanation of regex:

[^a-zA-Z0-9]

Match a single character NOT present in the list below «[^a-zA-Z0-9]»
   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»


Created with RegexBuddy

Comments (no comments yet)

Top Posts