Regular expression question

I'd like to make sort of a comment remover for C++.

If there's a source file like bellow...

<source.txt>
// 1234
12//34
///1234
12///34

and my code is...

file = open("source.txt", "r")
file.each_line {|line|
   if line.match /(.*)\/\//
      puts $1 if $1.length > 0
   end
}
file.close

result is...

12
  /
12/

but!, what I expected is~

12
12

What's wrong with this code...(I think I may not understand regular
expression totally...) and what should I do for this?

.* tries to match as much as possible (greedy) so the \/\/ will match the
last // it finds - not the first. If you want to make the .* non-greedy, add
a ? after the *.

HTH,
Sebastian

···

hongseok.yoon@gmail.com wrote:

file = open("source.txt", "r")
file.each_line {|line|
if line.match /(.*)\/\//
puts $1 if $1.length > 0
end
}
file.close

result is...

12
/
12/

but!, what I expected is~

12
12

--
Jabber: sepp2k@jabber.org
ICQ: 205544826

Additional remarks: using the block form of File.open is usually
better because code will be more robust. Here's another solution:

File.foreach "source.txt" do |line|
  puts line.sub(%r{//.*}, '')
end

Kind regards

robert

···

2008/5/26 <hongseok.yoon@gmail.com>:

I'd like to make sort of a comment remover for C++.

If there's a source file like bellow...

<source.txt>
// 1234
12//34
///1234
12///34

and my code is...

file = open("source.txt", "r")
file.each_line {|line|
  if line.match /(.*)\/\//
     puts $1 if $1.length > 0
  end
}
file.close

result is...

12
/
12/

but!, what I expected is~

12
12

What's wrong with this code...(I think I may not understand regular
expression totally...) and what should I do for this?

--
use.inject do |as, often| as.you_can - without end