Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 913
flow Avatar asked Jan 11 '23 10:01

flow


1 Answers

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.

like image 101
p.s.w.g Avatar answered Jan 18 '23 22:01

p.s.w.g