regular expression question...

H

hongseok.yoon

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?
 
S

Sebastian Hungerecker

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

result is...

12
=A0 /
12/

but!, what I expected is~

12
12

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

HTH,
Sebastian
=2D-=20
Jabber: (e-mail address removed)
ICQ: 205544826
 
R

Robert Klemme

2008/5/26 said:
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?

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,183
Latest member
OrderGlycoEase

Latest Threads

Top