Reputation: 5028
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
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
Reputation: 101681
It is possible without using regex:
str = str.Replace(" \"", "\\\"");
Upvotes: 0
Reputation: 623
Without a regex this should do:
yourStringVar.Replace("""","\\""").Replace("\\\\""","\\""");
Upvotes: 0
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