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 *
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:
\d{2,}
with *
,\d
with ?
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With