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();