Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing digits in C# string

Tags:

string

c#

regex

I am trying to use regular expressions to do some work on strings but I am having some difficulty. My goal is to replace numbers in a string with a character, specifically if there is a group of numbers in the string I want to replace the entire group of numbers with a *. If there is just a single digit I want to replace that with a ?.

For example, if I had the string "test12345.txt" I would like to turn that to "test*.txt", but if I have "test1.txt" I would like to turn that to just "test?.txt".

I tried

Regex r = new Regex(@"\d+", RegexOptions.None);
returnString = r.Replace(returnString, "*");

But this replaces replaces even a single digit on its own with a *

like image 855
DukeOfMarmalade Avatar asked Dec 21 '11 08:12

DukeOfMarmalade


3 Answers

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]", "?" );
like image 62
IanNorton Avatar answered Nov 03 '22 17:11

IanNorton


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.

like image 27
Abdul Munim Avatar answered Nov 03 '22 17:11

Abdul Munim


Do this with two regexes:

  • replace \d{2,} with *,
  • replace \d with ?.
like image 29
fge Avatar answered Nov 03 '22 16:11

fge