Replace a semi-simple string?

I have this text

'Random Text', 'a\nb\\c\'d\\', 'ok' 

I want him to become

 'Random Text', 'a\nb\c''d\', 'ok' 

The problem is coming out. Instead of escaping with \ , now I only run away with ' c '' . This is for a third-party program, so I can’t change it, so you need to change one screening method to another.

Problem \\' . If I replace the string, it will become \'' , not \' . Also, \n not a newline, but the actual text \n , which should not be changed. I tried using a regex, but I could not think of a way to say whether to replace ' with '' else if \\ replace with \ . Obviously, doing this in two steps creates a problem.

How to replace this line?

+4
source share
2 answers

If I understand your question correctly, the problem is replacing \\ with \ , which could lead to another replacement if it occurs immediately before ' . One method is to replace it with an intermediate line first, that you are sure that this will not happen anywhere, and then replace it after you are done.

 var str = @"'Random Text', 'a\nb\\c\'d\\', 'ok'"; str.Replace(@"\\", "NON_OCCURRING_TEMP") .Replace(@"\'", "''") .Replace("NON_OCCURRING_TEMP", @"\"); 

As pointed out by @AlexeiLevenkov, you can also use Regex.Replace to simultaneously work with both modifications.

 Regex.Replace(str, @"(\\\\)|(\\')", match => match.Value == @"\\" ? @"\" : @"''"); 
+6
source

It is understood that the interpretation of the Voithos question is correct. Another approach is to use RegEx to simultaneously search for all tokens and replace ReguarExpression.Replace

Starting point:

 var matches = new Regex(@"\\\\'|\\'|'"); Console.Write(matches.Replace(@"'ab\nc d\\e\'f\\'", match =>"["+match + "]")); 
+3
source

Source: https://habr.com/ru/post/1495802/


All Articles