From: "David A. Black" Date: 2009-01-25T04:58:52+09:00 Subject: Re: how to find the position of each match within a string Hi -- On Sun, 25 Jan 2009, Li Chen wrote: > > Hi all, > > I have a small script to find a match. If a match is found I need to > print its position within the string. I try the String#index but it only > returns the first match. Any idea? > > Thanks, > > Li > > C:\Documents and Settings\chen73\My Documents\Ruby\bin>irb > irb(main):001:0> "ello-hello".scan('e') do |match| > irb(main):002:1* p "ello-hello".index(match) > irb(main):003:1> end > 0 > 0 > => "ello-hello" You can examine the $~ global MatchData object, in a couple of ways: irb(main):003:0> "ello-hello".scan('e') do |match| irb(main):004:1* p $~.pre_match.size irb(main):005:1> end 0 6 => "ello-hello" irb(main):006:0> "ello-hello".scan('e') do |match| irb(main):007:1* p $~.offset(0)[0] irb(main):008:1> end 0 6 => "ello-hello (And there may be more I'm not thinking of.) David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) http://www.wishsight.com => Independent, social wishlist management!