From: Michael Fellinger Date: 2008-02-24T14:33:58+09:00 Subject: Re: [Q] difference between StringScanner#scan and Regexp#match On Sun, Feb 24, 2008 at 1:20 PM, makoto kuwata wrote: > Hi, > > I'm planning to implement StringScanner in pure Ruby. > But I found that it is hard to implement StringScanner#scan() > in pure Ruby, because of the difference between Regexp#match() > and StringScanner#scan(). > > StringScanner#scan() matches only when pattern matches at the > beginning (or at the current position) of input string. > > require 'strscan' > input = 'foo 123' > scanner = StringScanner.new(input) > p scanner.scan(/\d+/) #=> nil > > But Regexp#match() matches whenever input string contains pattern. > > input = 'foo 123' > m = /\d+/.match(input) > p m[0] if m #=> "123" > > > Is it possible to restrict Regexp#match() to match only when > pattern starts at the beginning of input string? > My idea is to convert /regexp/ into /\A(?:regexp)/ every time, > but it is a litte ugly. > Is there any good idea to emulate StringScanner#scan in pure Ruby? input = 'foo 123' if (input =~ /\d+/) == 0 p $& # doesn't happen end