Reputation: 548
I have a string like this:
var path = "'Ah'This is a 'sample\'e'";
In the above string beginning and ending single quote(after double quotes) are as expected.
i.e "'...............'";
In the rest part of the string, there are single quotes (both replaced (i.e \' and un-replaced). I have a necessity to replace the single quote wherever it is not replaced. If it is already escaped, then no action needed. I have a hard time to find suitable regex to replace this.
After replacing the string must look like this( Please note that beginning and ending single quotes must not be replaced.
"'Ah\'This is a \'sample\'e'";
Could someone please help?
Upvotes: 0
Views: 684
Reputation: 627535
You may use
s = Regex.Replace(s, @"(?<!\\)(?!^)'(?!$)", @"\'");
See the regex demo. Regex graph:
Details
(?<!\\)
- a negative lookbehind that matches a location in string that is not immediately preceded with \
(?!^)
- a negative lookahead that matches a location in string that is not immediately followed with start of string (it is just failing the match if the current position is the start of string)'
- a '
char(?!$)
- a negative lookahead that matches a location in string that is not immediately followed with the end of string (it is failing the match if the current position is the end of string).Upvotes: 1