I want to replace all occurrences "with \"in in a line, except that it is "preceded by \ for example, the line hello "World\"will becomehello \"World\"
"
\"
\
hello "World\"
hello \"World\"
Is this possible without using regex? But if I need to use a regex, what type should I use?
Thanks for the help, Regards,
You can use lookbehind:
var output = Regex.Replace(input, @"(?<!\\)""", @"\""")
Or you can just make the previous character optional, for example:
var output = Regex.Replace(input, @"\\?""", @"\""")
, " \" ( , ), \" \", .
:
(?<!\\)"
yourStringVar.Replace("""","\\""").Replace("\\\\""","\\""");
str = str.Replace(" \"", "\\\"");
, , String.Replace. StringBuilder:
String.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();
: ( ): http://ideone.com/Xmeh1w