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 m
MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx\r\nMTExMTExMTExMTExMQ==\r\n
=> nil

 

 

你可能感兴趣的:(Ruby)