如何在Ruby字符串的開頭和結尾刪除換行

[英]How to remove newLines at the beginning and at the end of a Ruby string


I need to remove newlines at the beginning and at the end of a string in ruby (some sort of trimming).

我需要在ruby中的字符串的開頭和結尾刪除換行(某種修飾)。

But JUST at the beginning and the end... The new lines located in the middle of the string must remain untouched.

但就在開頭和結尾……位於字符串中間的新行必須保持原狀。

Thank you!

謝謝你!

5 个解决方案

#1


29  

You can use String#strip method.

您可以使用String#strip方法。

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

#2


3  

String.strip will remove all extra whitespace from the front and back, leaving innards alone.

字符串。條帶將從前面和后面刪除所有額外的空白,只留下內部空白。

http://ruby-doc.org/core/classes/String.html#M001189

http://ruby-doc.org/core/classes/String.html M001189

#3


1  

If your intent is to strip just whitespace then the strip method should work...but if your trying to target new lines specifically then maybe try this:

如果您的目的是刪除空白,那么條帶方法應該可以工作……但是,如果你想專門針對新系列,那么不妨試試這個:

"\r\na b c d\r\ne f g\r\n".gsub(/^\r\n/, "").gsub(/\r\n$/, "")
=> "a b c d\r\ne f g"

the gsub method will use regular expression to target the beginning ^ and end $ locations for replacement with "".

gsub方法將使用正則表達式的目標一開始^和結束位置與“替代美元。

NOTE: Here I made the assumption that your newline is \r\n. This may not be platform independent.

注意:這里我假設您的新行是\r\n。這可能不是平台獨立的。

#4


1  

The platform independent version of NPatel's answer is:

NPatel的獨立於平台的回答是:

"\nabc\ndef\n".gsub(/^#{$/}/, "").gsub(/#{$/}$/, "")

#5


0  

This should do it:

這應該這樣做:

string.lstrip!.rstrip!

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/08/23/5d3caf1ed6fe9e1f6ded07aca1ad9896.html



 
  © 2014-2022 ITdaan.com 联系我们: