简体   繁体   English

C# 正则表达式中的 Escaping C++ 代码

[英]Escaping C++ code in C# Regex

Im trying to insert literal strings into c++ files using a c# tool, and Im tasked with automatically adding escapes.我试图使用 c# 工具将文字字符串插入 c++ 文件,并且我的任务是自动添加转义。

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 =(上面的代码对我的字符串没有任何作用,导致未转义的引号和损坏的代码文件 =(

Well, you've got:嗯,你有:

// ...
return content;

...which simply returns the string passed in. So, all of that Regex.Replace goodness gets thrown away. ...它只是返回传入的字符串。因此,所有Regex.Replace的优点都被丢弃了。

For this simple task, you don't really need a regexp.对于这个简单的任务,您实际上并不需要正则表达式。 Using String.Replace() is straightforward.使用String.Replace()很简单。

String.Replace Method String.Replace方法

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.返回一个新字符串,其中在此实例中出现的所有指定 Unicode 字符或字符串都替换为另一个指定的 Unicode 字符或字符串。

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>

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.对我来说,上面的 output 看起来不错。

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

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