views:

115

answers:

3

Im trying to insert literal strings into c++ files using a c# tool, and Im tasked with automatically adding escapes.

To start with " => \". However I cannot figure out the regular expression required to transform instances of " to \"

    public String AddEscapeCharactersForCode(String content)
    {
        String escaper = "\\\\";
        String ncontent = Regex.Replace(content, "\\\\\"");
        ncontent = Regex.Replace(ncontent, "'", "\\\\'");
        ncontent = Regex.Replace(ncontent, "\n", "\\\\\n");
        return content;
    }

The above code does nothing to my strings resulting in unescaped quotes and broken code files =(

+4  A: 

Well, you've got:

// ...
return content;

...which simply returns the string passed in. So, all of that Regex.Replace goodness gets thrown away.

Roger Lipscombe
As an alternative, use "return ncontent;"
luiscubal
+3  A: 

For this simple task, you don't really need a regexp. Using String.Replace() is straightforward.

String.Replace Method

Returns a new string in which all occurrences of a specified Unicode character or String in this instance are replaced with another specified Unicode character or String.

s1 = "some \"parts\" may be \"quoted\" here"
// s1 is <some "parts" may be "quoted" here>
s2 = s.replace("\"", "\\\"")
// s2 is <some \"parts\" may be \"quoted\" here>
gimel
+1  A: 

If you must do it with regex, minimize the number of replacements by using a regular expression that handles backslashes and double quotes in one step.

public String AddEscapeCharactersForCode(String content)
{
  content = Regex.Replace(content, "[\"\\\\]", "\\$&");
  content = Regex.Replace(content, "\n", "\\n");
  return content;
}

I think you have too many backslashes in your example. To me the output of the above looks right.

Tomalak