How to use Regex.Replace to Replace Two Strings at

2020-03-06 02:36发布

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

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, "#", "_");
 }

标签: c# regex replace
2条回答
▲ chillily
2楼-- · 2020-03-06 03:23

And just for fun, you can accomplish the same thing with 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())
查看更多
劫难
3楼-- · 2020-03-06 03:29

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('\'', '_');
查看更多
登录 后发表回答