0

I am looking for a 'Regex' to replace \n\ from my string. 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).

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. When I try below code,

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

It says parsing "\n\" - Illegal \ at the end of pattern . Can you anyone please help me with the same. Thanks in advance.

Community
  • 1
  • 1
Sibeesh Venu
  • 18,755
  • 12
  • 103
  • 140

3 Answers3

4

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.

Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
  • 3
    `regout` is just a lie now :) – Jonesopolis Dec 21 '16 at 13:55
  • @CyrilGandon Thanks, but if I use `String.Replace` it will be removing only one occurrence right? – Sibeesh Venu Dec 21 '16 at 14:01
  • nop, every occurence will be replaced, see @RajshekarReddy screenshot : http://stackoverflow.com/a/41264492/128662 – Cyril Gandon Dec 21 '16 at 14:03
  • @CyrilGandon Thanks much, I totally lost my control, thanks much for the light. What I was doing is, checking the value of `eneteredString` after the statement `eneteredString.Replace(@"\n\", "")` instead of assigning that value to some other string variable and check. – Sibeesh Venu Dec 21 '16 at 14:07
  • @CyrilGandon Just curious to know, what if I need to add the values we get after the `Replace` to a `List`? Can we do that without looping through? – Sibeesh Venu Dec 21 '16 at 14:18
  • I'm not sure what you mean. Adding the string to a List? maybe you should ask a new question. – Cyril Gandon Dec 21 '16 at 14:35
1

use @"\\n\\" . You need to remove the meaning of the escape character \ by adding a \ before it.. Here is a testing image

enter image description here

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
0

This is what you want. The reason is due to how regex handles the single \

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