From: Robert Klemme Date: 2010-03-27T07:05:08+09:00 Subject: Re: index of string from beginning of line vs beginning of file On 03/26/2010 09:48 PM, Jesús Gabriel y Galán wrote: > On Fri, Mar 26, 2010 at 5:17 PM, Jesse B. wrote: >> Thank You Robert, >> I tried running this and unfortunately it shows the line break (newline) >> with or without the leading space before the "comment". >> >> So I think Jesus is unto something with the "joined the array before >> writing it because puts with an array prints a newline between each >> element." >> >> Now I just need to figure out how to have it not do the newline when >> there are spaces before the "comment" >> thanks for your time. > > I think there's no solution to that. I mean, the requirement is to > remove what's inside the comments, and that leaves a line with a > single space. Both my solution and Robert's do exactly that (I think > Robert's solution is the better one). > > What you are asking now is for an additional condition, that it might > be that if after removing the comments there's an empty line (a line > with only spaces), that should be removed too. > > content = File.read "input.txt" > content.gsub! %r{--/.*?/--}m, '' > content.gsub! %r{\A\s+\z}, '' # untested and i think you might to > remove a \n in this case too, give it a try. > > File.open "output.txt", "w" do |out| > out.write content > end > > > Or maybe the condition is to remove all the whitespace and \n that > surround the comments. > > content = File.read "input.txt" > content.gsub! %r{[\n\s]*--/.*?/--[\n\s]*}m, '' #untested also, but > you get the idea. > > File.open "output.txt", "w" do |out| > out.write content > end > > Hope this helps, A bit more to play with content = File.read "input.txt" content.gsub! %r{^[ \t]*--/(?:.(?!/--))*.?/--\s*?$\s}m, '' content.gsub! %r{[ \t]*--/(?:.(?!/--))*.?/--[ \t]*}m, ' ' File.open "output.txt", "w" do |out| out.write content end I used this for testing: robert@fussel:~$ cat input.txt 1. before after X1.1 before --/ comment comment /-- after X1.2 2. before X2.1 before --/ comment comment /-- X2.2 3. after X3.1 --/ comment comment /-- after X3.2 4. - X4.1 --/ comment comment /-- X4.2 5. end robert@fussel:~$ ;-) Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/