ruby 删除String中的多个空格和新行

ecfdbz9o  于 2022-12-22  发布在  Ruby
关注(0)|答案(9)|浏览(164)

假设我们有这样的字符串:

Hello, my\n       name is Michael.

我怎么才能去掉新的一行,然后把后面的空格,放到字符串里面呢?

Hello, my name is Michael.
eanckbw9

eanckbw91#

查看Rails squish方法:
https://api.rubyonrails.org/classes/String.html#method-i-squish

cyej8jka

cyej8jka2#

举例说明squeeze中内置的Rubys:

string.gsub("\n", ' ').squeeze(' ')
cgh8pdjw

cgh8pdjw3#

最简单的方法可能是

s = "Hello, my\n       name is Michael."
s.split.join(' ') #=> "Hello, my name is Michael."
rbl8hiat

rbl8hiat4#

试试这个:

s = "Hello, my\n       name is Michael."
s.gsub(/\n\s+/, " ")
2ic8powd

2ic8powd5#

my_string = "Hello, my\n       name is Michael."
my_string = my_string.gsub( /\s+/, " " )
fquxozlt

fquxozlt6#

此正则表达式将用1个空格替换1个或多白色的示例,p.s \s将替换所有空格字符,包括\s\t\r\n\f

a_string.gsub!(/\s+/, ' ')

同样,仅回车

str.gsub!(/\n/, " ")

首先用白色替换所有的\n,然后使用remove multiple white space regex。

x3naxklr

x3naxklr7#

使用字符串#gsub:

s = "Hello, my\n       name is Michael."
s.gsub(/\s+/, " ")
yvgpqqbh

yvgpqqbh8#

Use squish
currency = " XCD"
str = currency.squish
 str = "XCD" #=> "XCD"
l5tcr1uw

l5tcr1uw9#

你可以只添加squish方法(不添加其他方法)到Ruby中,只要包含这个Ruby Facet:
https://github.com/rubyworks/facets/blob/master/lib/core/facets/string/squish.rb

require 'facets/string/squish'

然后使用

"my    \n   string".squish #=> "my string"

不需要Rails。

相关问题