DukeOfMarmalade
DukeOfMarmalade

Reputation: 2788

C# Replace group of numbers in a string with a single character

Does anybody know I can replace a group of numbers in a string by one *. For example if I have a string like this "Test123456.txt", I want to convert it to "Test#.txt". I have seen plenty of examples that can replace each individual number with a new character, but none that deal with a group of numbers. Any help is much appreciated!

Upvotes: 0

Views: 188

Answers (3)

Muad'Dib
Muad'Dib

Reputation: 29196

you can use regex, to do this, but if you know the exact text, then using the string.Replace method would be more efficient:

string str =  "blahblahblahTest123456.txt";
str = string.Replace("Test#.txt","Test123456.txt");

Upvotes: 1

Phil Klein
Phil Klein

Reputation: 7514

Use Regex.Replace() as follows:

string fileName = "Test12345.txt";
string newFileName = Regex.Replace(fileName, @"[\d]+", "#");

Upvotes: 1

Ta01
Ta01

Reputation: 31610

Regex r = new Regex(@"\d+", RegexOptions.None);
            Console.WriteLine(r.Replace("Test123456.txt", "#"));
            Console.Read();

Upvotes: 5

Related Questions