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). :)
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.
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 .
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/," ")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With