Replace single backslash with double backslash

前端 未结 5 2146
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 18:59

It seems simple enough, right? Well, I don\'t know.

Here\'s the code I\'m trying:

input = Regex.Replace(input, \"\\\\\", \"\\\\\\\\\\\\\");


        
相关标签:
5条回答
  • 2020-12-18 19:25
     var result = Regex.Replace(@"afd\tas\asfd\", @"\\", @"\\");
    

    The first parameter is string \\ which is \ in regex.
    The second parameter is not processed by regex, so it will put it as is, when replacing.

    0 讨论(0)
  • 2020-12-18 19:26

    If you intend to use the input in a regex pattern later, it can be a good idea to use Regex.Encode.

    input = Regex.Escape(input);
    
    0 讨论(0)
  • 2020-12-18 19:27

    The first one should be "\\\\", not "\\". It works like this:

    • You have written "\\".
    • This translates to the sequence \ in a string.
    • The regex engine then reads this, which translates as backslash which isn't escaping anything, so it throws an error.

    With regex, it's much easier to use a "verbatim string". In this case the verbatim string would be @"\\". When using verbatim strings you only have to consider escaping for the regex engine, as backslashes are treated literally. The second string will also be @"\\", as it will not be interpreted by the regex engine.

    0 讨论(0)
  • 2020-12-18 19:34

    I know it's too late to help you, maybe someone else will benefit from this. Anyway this worked for me:

    text = text.Replace(@"\",@"\\");
    

    and I find it even more simplier.

    Cheers!

    0 讨论(0)
  • 2020-12-18 19:44

    If you want to replace one backslash with two, it might be clearer to eliminate one level of escaping in the regular expression by using @"..." as the format for your string literals, also known as a verbatim string. It is then easier to see that

    string output = Regex.Replace(input, @"\\", @"\\");
    

    is a replacement from \ to \\.

    0 讨论(0)
提交回复
热议问题