C# 如何使用 Regex.Replace 一次替换两个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1044353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Regex.Replace to Replace Two Strings at Once?
提问by
I have the following method that is replacing a "pound" sign from the file name but I want also to be able to replace the "single apostrophe ' " at the same time. How can I do it? This is the value of filename =Provider license_A'R_Ab#acus Settlements_1-11-09.xls
我有以下方法可以替换文件名中的“井号”符号,但我也希望能够同时替换“单撇号 '”。我该怎么做?这是 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, "#", "_");
}
采纳答案by Jon Skeet
Try
尝试
return Regex.Replace(filename, "[#']", "_");
Mind you, I'm not sure that a regex is likely to be faster than the somewhat simpler:
请注意,我不确定正则表达式可能比更简单的更快:
return filename.Replace('#', '_')
.Replace('\'', '_');
回答by Judah Gabriel Himango
And just for fun, you can accomplish the same thing with LINQ:
只是为了好玩,你可以用 LINQ 完成同样的事情:
var result = from c in fileName
select (c == '\'' || c == '#') ? '_' : c;
return new string(result.ToArray());
Or, compressed to a sexy one-liner:
或者,压缩成性感的单线:
return new string(fileName.Select(c => c == '\'' || c == '#' ? '_' : c).ToArray())