C # replace a string, unless another is preceded by another

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\"

Is this possible without using regex? But if I need to use a regex, what type should I use?

Thanks for the help, Regards,

+4
source share
5 answers

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, @"\\?""", @"\""")

, " \" ( , ), \" \", .

+6

:

(?<!\\)"
+3

:

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

:

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

, , 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

0

All Articles