On 25.11.2007 16:39, Eric I. wrote: > On Nov 25, 10:18 am, makoto kuwata <k... / kuwata-lab.com> wrote: >> Hi, all. >> >> Is it possible to specify start position of Regexp matching? >> >> str = "foo bar baz" >> m = /ba/.match(str) >> p m.begin(0) #=> 4 >> m = /ba/.match(str, 5) # is it possible? >> p m.begin(0) #=> 8 (if possible) >> >> If it is possible, some kind of parser or scanner can be >> implemented easily. >> # StringScanner is a litte too big, I think. > > You could try something like this: > > m = /^.{5,}(ba)/.match(str) > p m.begin(1) > > In the regular expression, you're saying start at the beginning and > skip at least 5 characters. But then we have to use parens to "note" > the part you're interested in, and then we have to pass 1 rather than > 0 to begin, so it reports the location of the first noted match (0 > would report where the entire Regexp matched, and that would be the > beginning of the line). > > An alternative would be to slice the first n characters off the front > of the string and then do the match. Another alternative is to use String#scan - we would have to know what the OP really wants to parse though to decide whether it's a feasible solution. Kind regards robert