flow
flow

Reputation: 5028

C# replace string except when preceded by another

I want to replace all ocurrence of " by \" in a string except if this " is preceded by a \ for exemple the string hello "World\" will become hello \"World\"

Is it possible without using regex ? But if I have to use regex, what kind have I to use ?

Thanks for help, regards,

Upvotes: 4

Views: 978

Answers (5)

Tim Schmelter
Tim Schmelter

Reputation: 460038

Since you have asked if it's possible without using regex explicitly, that's not as simple and impossible with pure String.Replace approaches. You could use a loop and a 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();

Edit: here's a demo (difficult to create that string literal): http://ideone.com/Xmeh1w

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

It is possible without using regex:

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

Upvotes: 0

David
David

Reputation: 623

Without a regex this should do:

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

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 148980

You could use a lookbehind:

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

Or you could just make the preceeding character optional, for example:

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

This works because " is replaced with \" (which is what you wanted), and \" is replaced with \", so no change.

Upvotes: 6

Bryan Elliott
Bryan Elliott

Reputation: 4095

The regex for this would be:

(?<!\\)"

Upvotes: 3

Related Questions