Forum: Ruby Regular Expression matching biggest possible

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
unknown (Guest)
on 2006-04-01 20:00
(Received via mailing list)
Hi,

I would like to remove comments from a JavaScript file with a Ruby
script. I discovered that my regular expression matching seems to match
the biggest possible substring.

def show_regexp(a,re)
  if a =~ re
    "#{$`}<<#{$&}>>#{$'}"
  else
    "no match"
  end
end
puts show_regexp("/* some comment */ some code /* some other comment
*/", /\/\*[\w\W]*\*\//)

This outputs

<</* some comment */ some code /* some other comment */>>

and I was hoping for it to find the individual comments.

<</* some comment */>> some code <</* some other comment */>>

What should my regular expression be?

Thanks,
Peter
Chris A. (Guest)
on 2006-04-01 20:12
(Received via mailing list)
You can make a regexp non greedy with a ?, that is

/\/\*[\w\W]*?\*\//
                ^
unknown (Guest)
on 2006-04-01 21:01
(Received via mailing list)
Chris A. wrote:
> You can make a regexp non greedy with a ?, that is
>
> /\/\*[\w\W]*?\*\//

Thanks Chris,

Now I can easily find what i need in the manual:)

Peter
Damphyr (Guest)
on 2006-04-01 22:42
(Received via mailing list)
removed_email_address@domain.invalid wrote:
> Hi,
>
> I would like to remove comments from a JavaScript file with a Ruby
> script. I discovered that my regular expression matching seems to match
> the biggest possible substring.
Wow, I only had to wait 20 minutes before posting (or you could have
checked the regexp madness thread).
Seems today is greedy regexp day :)
V.-

--
http://www.braveworld.net/riva
This topic is locked and can not be replied to.