如何使用 Ruby 删除回车符? [英] How do I remove carriage returns with Ruby?

查看:47
本文介绍了如何使用 Ruby 删除回车符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这段代码可以工作,但正则表达式永远不会匹配 \r\n.我已经查看了我在十六进制编辑器中读取的数据,并确认文件中确实存在十六进制 D 和十六进制 A 模式.

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.

我也试过正则表达式/\xD\xA/m 和/\x0D\x0A/m 但它们也不匹配.

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

这是我现在的代码:

   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). :)

推荐答案

当你做 puts 行 时你会得到什么?这会给你一个线索.

What do you get when you do puts lines? That will give you a clue.

默认情况下 File.open 以文本模式打开文件,因此您的 \r\n 字符将自动转换为 \n.也许这就是 lines 总是等于 lines2 的原因.要防止 Ruby 解析行尾,请使用 rb 模式:

By default File.open opens the file in text mode, so your \r\n characters will be automatically converted to \n. Maybe that's the reason lines are always equal to lines2. To prevent Ruby from parsing the line ends use the rb mode:

C:\> copy con lala.txt
a
file
with
many
lines
^Z

C:\> irb
irb(main):001:0> text = File.open('lala.txt').read
=> "a\nfile\nwith\nmany\nlines\n"
irb(main):002:0> bin = File.open('lala.txt', 'rb').read
=> "a\r\nfile\r\nwith\r\nmany\r\nlines\r\n"
irb(main):003:0>

但是从您的问题和代码中,我看到您只需要使用默认修饰符打开文件即可.您不需要任何转换,可以使用较短的 File.read.

But from your question and code I see you simply need to open the file with the default modifier. You don't need any conversion and may use the shorter File.read.

这篇关于如何使用 Ruby 删除回车符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆