我有以下方法从文件名中替换“磅”符号,但我也希望能够同时替换“单撇号”。我该怎么做? 这是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, "#", "_");
}
答案 0 :(得分:18)
尝试
return Regex.Replace(filename, "[#']", "_");
请注意,我不确定正则表达式可能比更简单的更快:
return filename.Replace('#', '_')
.Replace('\'', '_');
答案 1 :(得分:7)
只是为了好玩,你可以用LINQ完成同样的事情:
var result = from c in fileName
select (c == '\'' || c == '#') ? '_' : c;
return new string(result.ToArray());
或者,压缩成性感的单行:
return new string(fileName.Select(c => c == '\'' || c == '#' ? '_' : c).ToArray())