Replace non numeric characters from a string using regular expressions and make it a number

This code sample shows how to use regular expressions to replace all non numeric characters from a string and make a valid number.

Sometimes you may want to exclude the non numeric characters from a string and retain only the digits to make it a valid number. A typical example is order id in a sales order. Many companies add some extra characters as a prefix to the order number to identify the customer or vendor. However, those prefix may not have any real purpose in the data and may need to be stripped off before we can use that order number to retrieve the order details from database.

Regular expressions provide an easy way to remove all non numeric characters from the string.

Code sample:

string orderString = "PON63320";
string orderNumber = Regex.Replace(orderString, @"[^\d]", "");
int orderId = int.Parse(orderNumber);


Author: Pankaj Rajput05 Dec 2010 Member Level: Gold   Points : 0

Nice and usefull article.

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: