Regex.Replace
, digitsA C# Regex
can match numeric characters. This helps with certain requirements. Some programs need to remove digit character to clean up input data.
The "\d" metacharacter matches digit characters. Conversely the "\D" metacharacter matches non-digit characters. Uppercase means "not."
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.
RemoveDigits
static
method.string
specifies a single digit character (0 through 9). The characters are replaced with an empty string
.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
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
.
string
using the new string
constructor.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.