在字符串中转义反斜杠 [英] Escaping backslashes in string

查看:219
本文介绍了在字符串中转义反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是在字符串中避免斜杠的好方法,而不会增加不必要的斜杠。

I would like to know what is a good way to escape back slashes in a string without adding unnecessary slashes to it.

我的意思是,通常如果我想在字符串中转义反斜杠,最简单的方法是使用 String.Replace(),如下所示:

I mean, usually if I want to escape a backslash in a string, the simplest way is to use String.Replace() like so:

string s = someString.Replace(\\,\\\\);

使用 Regex.Replace()的正则表达式可以完成类似的事情。

A similar thing can be done with regular expressions using Regex.Replace().

现在我的问题是,让我说我有一个字符串,它的一些背斜线转义例如:C:\some_folder\\some_file.bin

Now my question is, lets say I have a string that has some of its back slashes escaped like for example: "C:\some_folder\\some_file.bin"

现在,如果我尝试替换反斜杠,那么在每次出现之前添加一个反斜杠,我将最终得到以下字符串:

Now if I try and replace the backslashes in that by adding another backslash before each occurrence, I will end up with the following string:

C:\\\some_folder\\\\\some_file.bin

不清楚, \\\\ 是不必要的那么我该怎么去忽略已经转义的字符?

No clearly, the \\\\ are unnecessary, so how do I go about ignoring already escaped characters?

推荐答案

我想,这是你想要做的 - / p>

I think, this is what you want to do-

   string path = @"C:\some_folder\\some_file.bin";
   string exactPath = string.Join("\\",path.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries));

这篇关于在字符串中转义反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆