当前位置: 代码迷 >> Ruby/Rails >> ruby中替换换行符技艺
  详细解决方案

ruby中替换换行符技艺

热度:217   发布时间:2016-04-29 02:23:14.0
ruby中替换换行符技巧

我有一段文本:

str_encode = "MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx\nMTExMTExMTExMTExMQ==\n"

?想替换其中的"\n"为"\r\n",就是把<LF>全局替换为<CRLF>

?

代码如下:

irb(main):037:0> m = a.gsub(/\n/, "\r\n")=> "MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx\r\nMTExMTExMTExMTExMQ==\r\n"

?

-------------------------------------------------万恶的分割线-------------------------------------------------------------------

另附错误替换示例

irb(main):038:0> m = a.gsub(/\n/, '\r\n')

?这个错误代码中将"\n"替换成"\\r\\n"
结果如下:

=> "MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx\\r\\nMTExMTExMTExMTExMQ==\\r\\n"

?打印结果如下:

irb(main):039:0> puts mMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx\r\nMTExMTExMTExMTExMQ==\r\n=> nil

?

?