From: Brian Candler Date: 2003-06-28T00:23:32+09:00 Subject: Re: \s in regex > > what I want is to remove beginning and trailing spaces from lines. > > > > this is a failed try. > > > > ifile.each { | line | > > ofile.print line.sub(/^\s+/,"").sub(/\s+$/,"") > > } > > > > this removes spaces from begin and end of lines > > but it also removes blank lines. > > it seems \s matches \r or \n also. A blank line will be seen as "\n" in your example, and yes it is eaten by \s: irb(main):001:0> "\n".sub(/^\s+/,"") => "" But it's not eaten at the other end, since $ doesn't match the end of string, it matches before the newline: irb(main):002:0> "\n".sub(/\s+$/,"") => "\n" So you can solve it like this: line.sub(/^\s*(.*?)\s*$/,'\1') where .*? means "match any character any number of times, but eat as few characters as possible whilst still allowing the whole regexp to match" Or else, as others have mentioned, just remove it anyway (String#strip does this) and add a "\n" back again. Regards, Brian.