Skip to main content

Replacing all non numeric characters from a string using Regex

Use this simple snipet to remove all dashes and dots from document numbers, license plates and so on

Posted in C#, Code snippets, Tutorials

Everybody who works coding something must use Regular Expressions (RegEx) at least once in a lifetime. They can be used for a lot of things but my favorite will be always matching and removing characters from a string.

One of the problems I always have developing softwares was with number formatting. While in the user interface we should allow dots and dashes as the user will never really care if he should or should not use it. In Brazil, for example, the postal code has the following format: 00000-000. Some people might put it without the dash. And that, my friend, will hurt the database.

One way to solve this is forcing the backend to keep only the numbers. Let's take a look on how to do it using Regex.Replace:

  1. Add the reference
    using System.Text.RegularExpressions;
  2. Use this line of code
    string onlyNumbers = Regex.Replace(str, "[^0-9]""");

And that's it!

Did you like the article?

You can subscribe and get them as soon they are online, share using the buttons bellow or leave a comment.

And you also can share using your favorite social network: