Pindub_Amateur
Pindub_Amateur

Reputation: 328

How to replace \r in a string in ruby

I have a string that looks like this.

mystring="The Body of a\r\n\t\t\t\tSpider"

I want to replace all the \r, \n, \t etc with a whitespace.

The code I wrote for this is :

mystring.gsub(/\\./, " ")

But this isn't doing anything to the string.

Help.

Upvotes: 2

Views: 3635

Answers (4)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

String#tr is designed for stream symbol substitution. It appears to be a bit quickier, than String#gsub:

mystring.tr "\r", ' '

It hasan insplace version also (this will replace all carriage returns, line feed and spaces with space):

mystring.tr! "\s\r\n\t\f", ' '

Upvotes: 3

Stefan
Stefan

Reputation: 114138

\r, \n and \t are escape sequences representing carriage return, line feed and tab. Although they are written as two characters, they are interpreted as a single character:

"\r\n\t".codepoints #=> [13, 10, 9]

Because it is such a common requirement, there's a shortcut \s to match all whitespace characters:

mystring.gsub(/\s/, ' ')
#=> "The Body of a      Spider"

Or \s+ to match multiple whitespace characters:

mystring.gsub(/\s+/, ' ')
#=> "The Body of a Spider"

/\s/ is equivalent to /[ \t\r\n\f]/

Upvotes: 8

Gagan Gami
Gagan Gami

Reputation: 10251

Stefen's Answer is really very Cool as always comeup with very short and clean solutions. But here what I tried to remove all special characters. [Posted as just optional solution] ;)

 > a = "The Body of a\r\n\t\t\t\tSpider"
 => "The Body of a\r\n\t\t\t\tSpider" 
 > a.gsub(/[^0-9A-Za-z]/, ' ')
 => "The Body of a      Spider" 

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342323

you can use strip , then add a space to your string

mystring.strip . " "

If you literally has \r\n\t in your string:

mystring="The Body of a\r\n\t\t\t\tSpider"
mystring.split(/[\r\t\n]/)

Upvotes: 0

Related Questions