how can we replace '
with \\'
in a string. (this can be done using Regex.IsMatch(), Regex.Matches(), Regex.Replace()
However, it should be done only if '
doesn't have \
or \\
before already. (this is where I am stuck)
That means find all '
which do not have \
or \\
before it and then add the same, i.e. '
replace with \\'
Example string: 'abcd\'efg'hijkl'mno\\'pqrs'
Resulting string: \\'abcd\\'efg\\'hijkl\\'mno\\'pqrs\\'
No need for regex, even.
var newStr = oldStr.Replace("\\'", "'").Replace("'", "\\'");
With regex, you can find all '
that don't have \\
before them with:
[^\\]'
I think @YoryeNathan wins. But just to teach a regex lesson, this is exactly what negative lookbehind assertions exist for. Replace
(?<!\\\\)'
with
\\'
Usage
string output = Regex.Replace(input, "(?<!\\\\)'", "\\'");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With