简体   繁体   English

如何使用C#在特殊字符之前放置转义字符?

[英]How Can I Put Escape Character before Special Characters using C#?

buildLetter.Append("</head>").AppendLine();
buildLetter.Append("").AppendLine();
buildLetter.Append("<style type="text/css">").AppendLine();

Assume the above contents resides in a file. 假设上述内容存在于文件中。 I want to write a snippet that removes any line which has empty string "" and put escape character before the middle quotations. 我想写一个片段,删除任何有空字符串“”的行,并在中间引号之前放置转义字符。 The final output would be: 最终的输出是:

buildLetter.Append("</head>").AppendLine();
buildLetter.Append("<style type=\"text/css\">").AppendLine();

The outer " .... " is not considered special chars. 外部“......”不被视为特殊字符。 The special chars may be single quotation or double quotation. 特殊字符可以是单引号或双引号。

I could run it via find and replace feature of Visual Studio. 我可以通过Visual Studio的查找和替换功能来运行它。 However, in my case i want it to be written in c# or VB.NET 但是,在我的情况下,我希望它用c#或VB.NET编写

Any help will be appreciated. 任何帮助将不胜感激。

Perhaps this does what you want: 也许这就是你想要的:

string s = File.ReadAllText("input.txt");
string empty = "buildLetter.Append(\"\").AppendLine();" + Environment.NewLine;
s = s.Replace(empty, "");
s = Regex.Replace(s, @"(?<="").*(?="")",
         match => { return match.Value.Replace("\"",  "\\\""); }
    );

Result: 结果:

buildLetter.Append("</head>").AppendLine();
buildLetter.Append("<style type=\"text/css\">").AppendLine();

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

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