简体   繁体   English

C#用单个字符替换字符串中的数字组

[英]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". 例如,如果我有一个类似“ Test123456.txt”的字符串,我想将其转换为“ 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! 任何帮助深表感谢!

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

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.Replace方法会更有效:

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

Use Regex.Replace() as follows: 使用Regex.Replace()如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM