How to use Regex.Replace to Replace Two Strings at Once?

后端 未结 2 1762
耶瑟儿~
耶瑟儿~ 2021-01-06 13:11

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 c

相关标签:
2条回答
  • 2021-01-06 13:40

    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())
    
    0 讨论(0)
  • 2021-01-06 13:50

    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('\'', '_');
    
    0 讨论(0)
提交回复
热议问题