Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove carriage returns with Ruby?

Tags:

regex

ruby

I thought this code would work, but the regular expression doesn't ever match the \r\n. I have viewed the data I am reading in a hex editor and verified there really is a hex D and hex A pattern in the file.

I have also tried the regular expressions /\xD\xA/m and /\x0D\x0A/m but they also didn't match.

This is my code right now:

   lines2 = lines.gsub( /\r\n/m, "\n" )    if ( lines == lines2 )        print "still the same\n"    else        print "made the change\n"    end 

In addition to alternatives, it would be nice to know what I'm doing wrong (to facilitate some learning on my part). :)

like image 883
Jeremy Mullin Avatar asked Nov 13 '08 18:11

Jeremy Mullin


People also ask

How do you remove carriage returns in Ruby?

chomp is a String class method in Ruby which is used to returns new String with the given record separator removed from the end of str (if present). chomp method will also remove carriage return characters (that is it will remove \n, \r, and \r\n) if $/ has not been changed from the default Ruby record separator, t.

How do I remove a carriage return from a string in Java?

replaceAll("\\n", ""); s = s. replaceAll("\\r", ""); But this will remove all newlines. Note the double \ 's: so that the string that is passed to the regular expression parser is \n .


2 Answers

Use String#strip

Returns a copy of str with leading and trailing whitespace removed.

e.g

"    hello    ".strip   #=> "hello"    "\tgoodbye\r\n".strip   #=> "goodbye" 

Using gsub

string = string.gsub(/\r/," ") string = string.gsub(/\n/," ") 
like image 126
Ian Vaughan Avatar answered Sep 22 '22 21:09

Ian Vaughan


Generally when I deal with stripping \r or \n, I'll look for both by doing something like

lines.gsub(/\r\n?/, "\n"); 

I've found that depending on how the data was saved (the OS used, editor used, Jupiter's relation to Io at the time) there may or may not be the newline after the carriage return. It does seem weird that you see both characters in hex mode. Hope this helps.

like image 31
localshred Avatar answered Sep 21 '22 21:09

localshred