Quickly Replace Non-Numeric characters In a String

If you have a requirement where in you do not want to prevent users from entering non-numeric characters in a textbox, however want to filter out all the non-numeric characters, then here's how to do so:

First import the namespace System.Text.RegularExpressions;

C#


    // Replace non-numeric characters 

    string str = "12d223*23#22";

    string newStr = Regex.Replace(str, @"[^\d]", "");

 

    // Displays 122232322



VB.NET


    ' Replace non-numeric characters 

    Dim str As String = "12d223*23#22"

    Dim newStr As String = Regex.Replace(Str, "[^\d]", "")

 

    ' Displays 122232322



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

3 comments:

Greg S said...

This was perfect - thanks for the great (and simple) post!

Anonymous said...

Regex.Replace has a speed problem, will be your slowest line on your code, use with caution.

Anonymous said...

THANKS !!!!!