Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to strip \r and \n or \r\n

Tags:

regex

ruby

I use the following regex to make newlines
tags:

str.gsub("\r\n", '<br>')

This works fine on a desktop. on an iphone text only has \n, it doesn't have the \r.

How can I make the regex support either? \r\n or just \n ?

Thanks

like image 602
AnApprentice Avatar asked Feb 02 '12 05:02

AnApprentice


People also ask

What is \r and \n in regex?

\n. Matches a newline character. \r. Matches a carriage return character.

What does \r do in regex?

Definition and Usage The \r metacharacter matches carriage return characters.

How do you match line breaks in regex?

If you want to indicate a line break when you construct your RegEx, use the sequence “\r\n”. Whether or not you will have line breaks in your expression depends on what you are trying to match. Line breaks can be useful “anchors” that define where some pattern occurs in relation to the beginning or end of a line.

How do you remove r and N from string?

Try this. text = text . Replace("\\r\\n", "");


2 Answers

I think

str.gsub(/\r?\n/, '<br>')

should do the job

like image 125
barley Avatar answered Sep 30 '22 05:09

barley


\r\n|\r|\n

That regular expression will also let you support Macs, which use \r alone as a line ending. Since regexes are greedy, they will match the \r\n as opposed to the individual ones if possible.

like image 29
Niet the Dark Absol Avatar answered Sep 30 '22 06:09

Niet the Dark Absol