我有以下方法从文件名替换"磅"符号,但我也希望能够同时替换"单撇号".我该怎么做?这是filename = Provider license_A'R_Ab#acus Settlements_1-11-09.xls的值
static string removeBadCharPound(string filename)
{ // Replace invalid characters with "_" char.
//I want something like this but is NOT working
//return Regex.Replace(filename, "# ' ", "_");
return Regex.Replace(filename, "#", "_");
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 18
尝试
return Regex.Replace(filename, "[#']", "_");
Run Code Online (Sandbox Code Playgroud)
请注意,我不确定正则表达式可能比更简单的更快:
return filename.Replace('#', '_')
.Replace('\'', '_');
Run Code Online (Sandbox Code Playgroud)
只是为了好玩,你可以用LINQ完成同样的事情:
var result = from c in fileName
select (c == '\'' || c == '#') ? '_' : c;
return new string(result.ToArray());
Run Code Online (Sandbox Code Playgroud)
或者,压缩成性感的单行:
return new string(fileName.Select(c => c == '\'' || c == '#' ? '_' : c).ToArray())
Run Code Online (Sandbox Code Playgroud)