4

Because \r\n are "special" chars in a regex I have a problem identifying what I actually need to put in my expression.

basically i have a string that looks something like ...

bla\r\nbla\r\nbla

.. and i'm looking to change it to ...

bla
bla  
bla

... using a regular expression.

Any ideas?

War
  • 8,539
  • 4
  • 46
  • 98
  • `s/\\r\\n/\n/` What language? – billc.cn Jul 18 '12 at 11:12
  • Please be more specific...Are you working on a plain Text file? Or are you coding in PHP, JAVA etc.?? – user871784 Jul 18 '12 at 11:13
  • i am taking the result of a soap call from a service which is encoded and basically removing the encoding so I can debug the result, but i don't want to "remove it" i need to change the chars in to what they should be. – War Jul 18 '12 at 11:15
  • i guess i could pull the string in to visual studio and do this with a simple replace string.Replace("\\r\\n", "\r\n") would be the equivelent i guess (not checked it though) (in C#) – War Jul 18 '12 at 11:16
  • ok do a search for \\r\\n and replace it with \n – user871784 Jul 18 '12 at 11:17

2 Answers2

10

\ is an escape character in regex and can be used to escape itself, meaning that you can write \\n to match the text \n.

Use the pattern \\r\\n and replace with \r\n.

Thorbear
  • 2,303
  • 28
  • 23
  • there's still some oddities but that must be how notepad++ is handling the expression or something (it's like its randomly removing the odd char, there's also a few more newlines than i was expecting so it's obviously matched more than it should have. – War Jul 18 '12 at 11:20
  • 1
    @Wardy What oddities are those? Remember that `\\r\\n` will not match `\r` alone or `\n` alone. Do you have an example string where it did not work as expected? – Thorbear Jul 18 '12 at 11:23
  • it's ok ... it solves my problem at least :) its stuff like "hello world\r\nhello world" is wierdly returning something random like "helo world(actual newline char)hello worl" ... no idea why ... probably a bug in notepad++ but im working on a string that represents the full content of an email so i only need certain key info and this is a quick fix to make it readable nothing more :) – War Jul 18 '12 at 11:56
1

You don't necessarily need regex for this (unless this is not the only thing you are replacing), but \r\n is the way to go in most variants of regex.

Examples:

  • PHP

    • $str = preg_replace("/\\r\\n/", "\r\n", $str); or
    • $str = str_replace('\r\n', "\r\n", $str); (or "\\r\\n" for the first argument)
  • Ruby

    • str = str.gsub(/\\r\\n/, "\r\n") or
    • str = str.gsub('\r\n', "\r\n")
mogelbrod
  • 2,246
  • 19
  • 20
  • yeh i was toying with the idea of pulling it in to Visual studio (since the code im working on was written in C# anyway) but i just wanted to grab the result from the wcf test client and paste it in to notepad++ for examination, the problem is i got \r\n instead of newlines in the test client result lol – War Jul 18 '12 at 11:58