Can I convert a C# string value to an escaped string literal

后端 未结 16 1015
时光取名叫无心
时光取名叫无心 2020-11-22 07:51

In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences.

If

16条回答
  •  萌比男神i
    2020-11-22 08:05

    Hallgrim's answer was excellent. Here's a small tweak in case you need to parse out additional whitespace characters and linebreaks with a c# regular expression. I needed this in the case of a serialized Json value for insertion into google sheets and ran into trouble as the code was inserting tabs, +, spaces, etc.

      provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
      var literal = writer.ToString();
      var r2 = new Regex(@"\"" \+.\n[\s]+\""", RegexOptions.ECMAScript);
      literal = r2.Replace(literal, "");
      return literal;
    

提交回复
热议问题