简体   繁体   English

如果包含转义的单引号,如何用文字替换单引号字符串?

[英]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. 我可以用其他一些字符序列(例如internal_value )代替\\' ,而不是执行字符串替换,但是如果我可以用正则表达式代替它,它将更加清晰。

You can use 您可以使用

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

( modified a bit from the bible of regex :- Mastering Regular expression ) 从regex圣经修改了一点:-掌握正则表达式

regexstorm demo regexstorm演示

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' '快乐\\' S'

'Other\\'s Jr.' “其他小”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM