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 P.ming 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"
If you’re just speaking of the space character and you want to replace
double-spaces (or triple-spaces or more) with just a single space, you
can
do this.
Stefano, Joe - thank you! I’m only just getting into regex, so I get
easily lost. You solved my problem - each in different ways. A lot of
bang for the buck, indeed!
Stefano, Joe - thank you! I’m only just getting into regex, so I get easily
lost. You solved my problem - each in different ways. A lot of bang for the
buck, indeed!
Another variant:
a.gsub(/[^\S\n]+/, " ")
That character class means “all characters that are not a non-space or
\n.” (The ^ is the “not” part.)
You might also be able to use squeeze:
p “abc def \n ghi\n”.squeeze # “abc def \n ghi\n”
though that’s going to be less versatile if you’re dealing, say, with
tabs.
Thanks, David. I continue to be amazed by the depth of your knowledge,
and outright cleverness. In pursuing this simply problem I’m
inadvertently learning a lot. I’m grateful. Thanks for your contribution
that process!
t.
–
Tom C., MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< [email protected] >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)