Alle Friday 06 February 2009, Tom Cloyd ha scritto:
> I'm trying to remove extra spaces from a long string which has some
> EOLs, using regex. It's not working. Here's a simple demo:
>
> irb(main):004:0> a="\n  abc\n  a  a  a"
> => "\n  abc\n  a  a  a"
> irb(main):005:0> a.gsub(/\s+/,' ')
> => " abc a a a"
>
> I've dug around in my regex references, and all I can say is that is
> hasn't been the least bit helpful. I'm probably not looking for the
> right thing.
>
> Can someone more knowledgeable tell me is there's a way to do this -
> remove extra spaces without removing the EOLs?
>
> Thanks!
>
> t.

According to "The Ruby Programming Language", \s is equivalent to " \t\n\r\f". 
So, if you want avoid removing newlines, you'll need to replace \s with
[ \t\r\f] or with a whitespace if you're only intersted in it:

a="\n  abc\n  a  a  a"
a.gsub(/ +/, ' ')
=>"\n abc\n a a a"

I hope this helps

Stefano