我试图使用正则表达式对字符串做一些工作,但我遇到了一些困难.我的目标是用字符替换字符串中的数字,特别是如果字符串中有一组数字我想用a替换整个数字组*.如果只有一个数字我想用a替换它?.
例如,如果我有字符串"test12345.txt",我想将其转换为"test*.txt",但如果我有"test1.txt",我想将其转换为"test?.txt" .
我试过了
Regex r = new Regex(@"\d+", RegexOptions.None);
returnString = r.Replace(returnString, "*");
Run Code Online (Sandbox Code Playgroud)
但这取代了一个单独的数字,而不是一个数字 *
Ian*_*ton 16
使用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]", "?" );
Run Code Online (Sandbox Code Playgroud)