From: Caleb Clausen Date: 2008-10-26T08:02:09+09:00 Subject: Re: regular expressions and conditionals On 10/25/08, Matt Harrison wrote: > I'm writting a little program to convert some source files to html. > > I'm using regexp's to determine the content of each line and format it > accordingly. For example, if the line starts with a #, then it should be > output with a div (and id set to 'comment'). > > The problem is with matching the regular expressions. If I do this: > > f = File.new("myfile", "r") > while !f.eof? > line = f.gets > > if line.match(/^# (.*)/) > puts "
#{line.match(/^# (.*)/)[0]}
" > end > end > I think what you're trying to write is a little more like this: f = File.new("myfile", "r") while line = f.gets if line.match(/^# (.*)/) line="
#{line.chomp}
\n" end puts line end > Then not only do I get the commen lines formatted properly, I also get a > "nil" for every other line in the file. I didn't see any nils when I ran it... it just didn't print anything but comments. Which would be because your original only printed lines back out if they matched your comment pattern. Why do you have a space after the # in your pattern? I've found it to be good luck to always escape # when in regexps, even if it isn't followed by a {. Probably a bug lurking in there.