Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#替换字符串,除非前面有另一个字符串_C#_Regex_String_Replace - Fatal编程技术网

C#替换字符串,除非前面有另一个字符串

C#替换字符串,除非前面有另一个字符串,c#,regex,string,replace,C#,Regex,String,Replace,我想将所有出现的“替换为字符串中的\”,除非该“前面有\ 例如,字符串hello“World\”将变成hello\“World\” 是否可以不使用正则表达式? 但是如果我必须使用正则表达式,我必须使用什么类型的正则表达式呢 谢谢你的帮助, 关于这一点,正则表达式是: (?<!\\)" (?您可以使用lookback: var output = Regex.Replace(input, @"(?<!\\)""", @"\""") 这是因为“被替换为\”(这是您想要的),而\“被替换

我想将所有出现的
替换为字符串中的
\”
,除非该
前面有
\
例如,字符串
hello“World\”
将变成
hello\“World\”

是否可以不使用正则表达式? 但是如果我必须使用正则表达式,我必须使用什么类型的正则表达式呢

谢谢你的帮助,
关于这一点,正则表达式是:

(?<!\\)"

(?您可以使用lookback:

var output = Regex.Replace(input, @"(?<!\\)""", @"\""")

这是因为
被替换为
\”
(这是您想要的),而
\“
被替换为
\”
,所以没有变化。

如果没有正则表达式,这应该可以:

yourStringVar.Replace("""","\\""").Replace("\\\\""","\\""");

不使用正则表达式也可以:

  str = str.Replace(" \"", "\\\"");

既然您已经询问是否可以不显式使用正则表达式,那么对于纯
字符串来说,这并不是那么简单和不可能的。替换
方法。您可以使用循环和
StringBuilder

StringBuilder builder = new StringBuilder(); 
builder.Append(text[0] == '"' ? "\\\"" : text.Substring(0, 1));
for (int i = 1; i < text.Length; i++)
{
    Char next = text[i];
    Char last = text[i - 1];
    if (next == '"' && last != '\\')
        builder.Append("\\\"");
    else
       builder.Append(next);
}
string result = builder.ToString();
StringBuilder=新建StringBuilder();
builder.Append(text[0]==''?“\\\\”:text.Substring(0,1));
for(int i=1;i

编辑:这里有一个演示(很难创建字符串文字):

旁注:如果这是关于字符转义的,那么请注意场景中的边缘情况,比如在
表单中处理源字符串\\“
。一个简单的正则表达式后面的查找可能不是答案。这个边缘情况可以递归地扩展为:当源字符串是
“World\\\”
?当字符串是
“World\\\\”
?等等。。。
StringBuilder builder = new StringBuilder(); 
builder.Append(text[0] == '"' ? "\\\"" : text.Substring(0, 1));
for (int i = 1; i < text.Length; i++)
{
    Char next = text[i];
    Char last = text[i - 1];
    if (next == '"' && last != '\\')
        builder.Append("\\\"");
    else
       builder.Append(next);
}
string result = builder.ToString();