Replacing digits in C# string

This is pretty easy with Regex.Replace

string input = "test12345.txt";

// replace all numbers with a single *
string replacedstar = Regex.Replace( input, "[0-9]{2,}", "*" );

// replace remaining single digits with ?
string replacedqm = Regex.Replace( input, "[0-9]", "?" );

This will do, first it will match more than two digits and replace the complete block with * and the 2nd statement is for if there's single digit, it will replace with ?'

var newFileName = Regex.Replace(fileName, @"\d{2,}", "*");
newFileName = Regex.Replace(fileName, @"\d", "?");

Hope this helps.


Do this with two regexes:

  • replace \d{2,} with *,
  • replace \d with ?.

Tags:

C#

String

Regex