Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a pattern in string only if a certain condition is satisfied - Regex

Tags:

string

c#

regex

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\\'

like image 818
Indigo Avatar asked Dec 07 '22 08:12

Indigo


2 Answers

No need for regex, even.

var newStr = oldStr.Replace("\\'", "'").Replace("'", "\\'");

With regex, you can find all ' that don't have \\ before them with:

[^\\]'
like image 132
SimpleVar Avatar answered May 02 '23 21:05

SimpleVar


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, "(?<!\\\\)'", "\\'");
like image 21
slackwing Avatar answered May 02 '23 20:05

slackwing