War
War

Reputation: 8628

Regex how to replace \r\n with an actual newline in string

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?

Upvotes: 5

Views: 17879

Answers (2)

mogelbrod
mogelbrod

Reputation: 2315

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")

Upvotes: 1

Thorbear
Thorbear

Reputation: 2343

\ 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.

Upvotes: 12

Related Questions