Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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?

like image 746
War Avatar asked Jan 17 '23 02:01

War


2 Answers

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

like image 79
Thorbear Avatar answered Jan 29 '23 13:01

Thorbear


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")
like image 41
mogelbrod Avatar answered Jan 29 '23 11:01

mogelbrod