简体   繁体   English

C#正则表达式转义和替换

[英]C# Regex escape and replace

I have an API that sends out documents to email. 我有一个API,可以将文档发送到电子邮件。 I'm using a paramater that allows me to specify the email message. 我正在使用允许我指定电子邮件消息的参数。 It requires line breaks to be in Json format (\\n). 它要求换行符为Json格式(\\ n)。 I'm using Regex to escape the textbox text like shown below. 我正在使用正则表达式来转义文本框文本,如下所示。

string JsonMessage = string.Format("{0}\n{1}", System.Text.RegularExpressions.Regex.Escape(this.txtMailMessage.Text), System.Text.RegularExpressions.Regex.Escape(this.txtMailMessage.Text));
        JsonMessage = JsonMessage.Replace("\r", "");
        Console.WriteLine(JsonMessage);

Here is a example output: 5\\r\\n5\\r\\n5 这是示例输出:5 \\ r \\ n5 \\ r \\ n5

As shown I'm trying to replace the \\r in order to achieve the "line break" in Json. 如图所示,我正在尝试替换\\ r以便在Json中实现“换行”。 So it would look like this: 5\\n5\\n5 所以它看起来像这样:5 \\ n5 \\ n5

What I can't seem to wrap me head around is that when I cast the JsonMessage = JsonMessage.Replace("\\r", ""); 我似乎无法JsonMessage = JsonMessage.Replace("\\r", "");是,当我JsonMessage = JsonMessage.Replace("\\r", ""); it does not replace the \\r 它不能代替\\ r

You need to use JsonMessage.Replace("\\\\r", ""); 您需要使用JsonMessage.Replace("\\\\r", "");
The \\\\ will be interpreted as a single backslash. \\\\将被解释为单个反斜杠。

Instead of replacing "\\r" with nothing try and replace "\\r\\n" with "\\n" as 而不是什么都不要替换“ \\ r”,请尝试将“ \\ r \\ n”替换为“ \\ n”

        string mystring = "5\r\n5\r\n5";
        mystring = mystring.Replace("\r\n", "\n");

This will produce "5\\n5\\n5" 这将产生“ 5 \\ n5 \\ n5”

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

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