Home
C#
Regex.Replace Digits Example
Updated Jan 8, 2025
Dot Net Perls
Regex.Replace, digits. A C# Regex can match numeric characters. This helps with certain requirements. Some programs need to remove digit character to clean up input data.
Metacharacters. The "\d" metacharacter matches digit characters. Conversely the "\D" metacharacter matches non-digit characters. Uppercase means "not."
Regex.Replace
Regex.Match
In this example, the characters with the exact values 0 through 9 must be removed from the string. They are not replaced with other characters but entirely removed.
Part 1 We specify 3 different example strings and pass them to the RemoveDigits static method.
Part 2 The "\d" pattern string specifies a single digit character (0 through 9). The characters are replaced with an empty string.
Result The 3 strings have their numbers removed. The Regex allocates new string data and returns a reference to that object data.
using System; using System.Text.RegularExpressions; class Program { /// <summary> /// Remove digits from string. /// </summary> public static string RemoveDigits(string key) { // Part 2: use Regex.Replace with a metacharacter, and replace with an empty string. return Regex.Replace(key, @"\d", ""); } static void Main() { // Part 1: remove the digits in these example input strings. string input1 = "Dot123Net456Perls"; string input2 = "101Dalmatations"; string input3 = "4 Score"; string value1 = RemoveDigits(input1); string value2 = RemoveDigits(input2); string value3 = RemoveDigits(input3); Console.WriteLine(value1); Console.WriteLine(value2); Console.WriteLine(value3); } }
DotNetPerls Dalmatations Score
Performance. The performance of Regex.Replace is far from ideal. For more speed, you could use a char array and dynamically build up the output string.
Finally You could return that character array as a string using the new string constructor.
String Constructor
Summary. You can remove number characters in strings using the C# language. This requirement is common, and useful in the real world. We proved the method's correctness.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 8, 2025 (new example).
Home
Changes
© 2007-2025 Sam Allen