Loading ...

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

Regex: Remove all non numeric characters from a string

 /5
0 (0votes)

In this blog I will show how to remove all non numeric characters from a string with REGEX. Let's say we have a string "(912)-555-7777" and  remove all non numeric characters so that the string looks like "9125557777". 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 = @"(912)-555-7777";

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

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

Output:

Below is the explanation of regex:

[^0-9]

Match a single character NOT in the range between “0” and “9” «[^0-9]»


Created with RegexBuddy

Comments (no comments yet)

Top Posts