gotqn
gotqn

Reputation: 43676

How to replace single quotes string with literal if it contains escaped single quotes?

I need to escape all single quotes strings with literals and I am using the following regular expression:

'[^']*'

It is working fine, except when I have escaped single quotes in the string that must be replaced itself. For example, for the following string:

[COMPUTE:{IIF([Client Name] LIKE '%Happy%', 'Happy\'s', 'Other\'s Jr.')}]

I have these matches:

%Happy%
Happy\
, 
s Jr.

I can replace the \' with some other sequence of characters (for example internal_value) and than to perform the string replacement, but it will be more clearer if I can do this with the regular expression instead.

Upvotes: 1

Views: 285

Answers (2)

juharr
juharr

Reputation: 32296

You just need a negative look behind. Basically just use a lazy match to anything .*? then you can put a negative look behind for a backslash (?<!\\) before the end single quote.

var reg = new Regex(@"'.*?(?<!\\)'");

foreach(Match m in reg.Matches(@"[COMPUTE:{IIF([Client Name] LIKE '%Happy%', 'Happy\'s', 'Other\'s Jr.')}]"))
    Console.WriteLine(m);

outputs

'%Happy%'

'Happy\'s'

'Other\'s Jr.'

Upvotes: 1

rock321987
rock321987

Reputation: 11042

You can use

'((?:[^'\\]+|\\.)*)'

(modified a bit from the bible of regex :- Mastering Regular expression)

regexstorm demo

Upvotes: 1

Related Questions