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

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

Hello, my\n       name is Michael.

我怎样才能删除这个新的行,并剥离这些空格后,成为一个字符串的内部得到这个?

Hello, my name is Michael.
73034 次浏览

The simplest way would probably be

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

Use String#gsub:

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

this regex will replace instance of 1 or more white spaces with 1 white space, p.s \s will replace all white space characters which includes \s\t\r\n\f:

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

Similarly for only carriage return

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

First replace all \n with white space, then use the remove multiple white space regex.

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

To illustrate Rubys built in squeeze:

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

Try This:

s = "Hello, my\n       name is Michael."
s.gsub(/\n\s+/, " ")
Use squish
currency = " XCD"
str = currency.squish
str = "XCD" #=> "XCD"

You can add just the squish method (and nothing else) to Ruby by including just this Ruby Facet:

https://github.com/rubyworks/facets/blob/master/lib/core/facets/string/squish.rb

require 'facets/string/squish'

Then use

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

Doesn't require Rails.