简体   繁体   English

正则表达式从C#中的字符串中删除\\ n \\(不是\\ n)

[英]Regex to remove \n\ from a string in C# (Not \n)

I am looking for a 'Regex' to replace \\n\\ from my string. 我正在寻找一个'Regex'来替换我的字符串中的\\n\\ I already looked thorough this post and other regex posts here, but in my case I need to remove the value \\n\\ from a string not a new line or ( \\n ). 我已经在这里仔细阅读了这篇文章和其他正则表达式文章,但就我而言,我需要从字符串中删除值\\n\\而不是新行或( \\n )。

For example: 例如:

string eneteredString = @"abc\n\def\n\ghi\n\\";

Here \\\\ can be found multiple times too. \\\\也可以多次找到。

I have already tried Replacing Enviornment.NewLine , as it is not a new line in my case, it also didn't work. 我已经尝试过Enviornment.NewLine ,因为在我看来这不是新行,所以它也不起作用。 When I try below code, 当我尝试以下代码时,

string regout = Regex.Replace(enteredString, @"\n\","");

It says parsing "\\n\\" - Illegal \\ at the end of pattern . 它说"\\n\\" - Illegal \\ at the end of pattern解析"\\n\\" - Illegal \\ at the end of pattern Can you anyone please help me with the same. 有人可以帮我吗? Thanks in advance. 提前致谢。

Who need regex? 谁需要正则表达式?

string regout = @"abc\n\def\n\ghi\n\\".Replace(@"\n\", "");

And just because quotes are cool, here is the famous : 而且因为引号很酷,所以这是著名的

Some people, when confronted with a problem, think "I know, I'll use regular expressions." 有些人在遇到问题时会认为“我知道,我会使用正则表达式”。 Now they have two problems. 现在他们有两个问题。

use @"\\\\n\\\\" . 使用@"\\\\n\\\\" You need to remove the meaning of the escape character \\ by adding a \\ before it.. Here is a testing image 您需要通过在转义字符\\之前添加\\来消除转义字符\\的含义。这是一个测试图像

在此处输入图片说明

This is what you want. 这就是你想要的。 The reason is due to how regex handles the single \\ 原因是由于正则表达式如何处理单个\\

string regout = Regex.Replace(enteredString, @"\\n\\","");

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

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