所以我需要从字符串中删除转义的反斜杠(在我的例子中,路径就像“C:\ Program Files(x86)\ Microsoft Office \ Office14 \ WINWORD.EXE \”)。
要替换我已经尝试过以下内容:
String openWith = "C:\\Program Files (x86)\\Microsoft Office\\Office14\\WINWORD.EXE"; string newString = openWith.Replace(@"\\", @"\"); openWith = openWith.Replace(@"\\", @"\"); openWith = Regex.Replace(openWith,"\\\\","\\");但这些都不起作用!! 有人能够向我解释为什么会这样吗?
先感谢您!
So I need to remove escaped backslashes from a string (in my case, a path simply like "C:\Program Files (x86)\Microsoft Office\Office14\WINWORD.EXE\").
To replace I've tried the following:
String openWith = "C:\\Program Files (x86)\\Microsoft Office\\Office14\\WINWORD.EXE"; string newString = openWith.Replace(@"\\", @"\"); openWith = openWith.Replace(@"\\", @"\"); openWith = Regex.Replace(openWith,"\\\\","\\");But none of these work!! Would anyone be able to explain to me why this may be?
Thank you in advance!
最满意答案
您的字符串不包含加倍的反斜杠。
"C:\\"的第一个反斜杠是一个转义字符,由C#编译器解释。 但是在运行时,字符串只包含单个反斜杠。 您可以通过显示字符串的值来证明这一点:
String openWith = "C:\\Program Files (x86)\\Microsoft Office\\Office14\\WINWORD.EXE"; Console.WriteLine(openWith);结果:
C:\Program Files (x86)\Microsoft Office\Office14\WINWORD.EXE请注意,输出中只有一个反斜杠。
看它在线工作: ideone
Your string doesn't contain doubled backslashes.
The first backslash in "C:\\" is an escape character which is interpreted by the C# compiler. At runtime however the string only contains single backslashes. You can prove this to yourself by displaying the value of the string:
String openWith = "C:\\Program Files (x86)\\Microsoft Office\\Office14\\WINWORD.EXE"; Console.WriteLine(openWith);Result:
C:\Program Files (x86)\Microsoft Office\Office14\WINWORD.EXENote that there are only single backslashes in the output.
See it working online: ideone
更多推荐
发布评论