Regular Expresion Needed

Hello,

I am fairly new to Ruby. I have some good Perl experience and I need
to "translate" a regex in Perl over to Ruby. Here's what I have:

$_ = 'abc123def456ghi789jkl';
while(m/(\d{4})/g)
{ print "$1\n"; }

Which outputs:
123
456
789

Ruby doesn't seem to have the same modifiers that Perl does (that
handy little g). How can I get this same output in Ruby? Thanks!

Matt White wrote:

Hello,

I am fairly new to Ruby. I have some good Perl experience and I need
to "translate" a regex in Perl over to Ruby. Here's what I have:

$_ = 'abc123def456ghi789jkl';
while(m/(\d{4})/g)
{ print "$1\n"; }

Which outputs:
123
456
789

Ruby doesn't seem to have the same modifiers that Perl does (that
handy little g). How can I get this same output in Ruby? Thanks!

'abc123def456ghi789jkl'.scan(/\d{3}/).each{|m| puts m}

···

--
Alex

Assume you meant to match \d{3} since \d{4} won't match anything in your
test string. Pass a regexp to String#scan:

irb(main):027:0>s = 'abc123def456ghi789jkl'
irb(main):028:0> s.scan(/(\d{3})/).each do |m|
irb(main):029:1* puts m
irb(main):030:1> end
123
456
789
=> [["123"], ["456"], ["789"]

···

On 6/19/07, Matt White <whiteqt@gmail.com> wrote:

Hello,

I am fairly new to Ruby. I have some good Perl experience and I need
to "translate" a regex in Perl over to Ruby. Here's what I have:

$_ = 'abc123def456ghi789jkl';
while(m/(\d{4})/g)
{ print "$1\n"; }

Which outputs:
123
456
789

Ruby doesn't seem to have the same modifiers that Perl does (that
handy little g). How can I get this same output in Ruby? Thanks!

--
Neil Kohl
nakohl@gmail.com

Hi,

···

Am Mittwoch, 20. Jun 2007, 04:05:07 +0900 schrieb Matt White:

I am fairly new to Ruby. I have some good Perl experience and I need
to "translate" a regex in Perl over to Ruby. Here's what I have:

$_ = 'abc123def456ghi789jkl';
while(m/(\d{4})/g)
{ print "$1\n"; }

Which outputs:
123
456
789

  'abc123def456ghi789jkl'.scan /\d{1,4}/ do |x| puts x end
  'abc123def456ghi789jkl'.scan /\d{1,4}/ do puts $& end
  'abc123def456ghi789jkl'.scan( /\d{1,4}/) { |x| puts x }
  'abc123def456ghi789jkl'.scan( /\d{1,4}/) { puts $& }

Bertram

--
Bertram Scharpf
Stuttgart, Deutschland/Germany
http://www.bertram-scharpf.de