From: Tim Pease Date: 2007-02-15T03:33:23+09:00 Subject: Re: Programmatically turning a Regexp into an anchored Regexp On 2/14/07, Greg Hurrell wrote: > Is there any programmatic way to take a Regexp like /foo/ and turn it > into an anchored Regexp (/^foo/)? I'm looking for a programmatic way > to do this because the actual Regexp is dynamic, not known until run > time. > > I'm wishing for an option or method similar to the EXTENDED, > IGNORECASE, MULTILINE options, except for anchoring. > > I suspect the answer will be "no", but I wanted to ask anyway before > giving up hope... def anchor( rgxp ) Regexp.new "^#{rgxp.inspect[1...-1]}" end I would recommend using the '\A' anchor instead of the '^' anchor. '^' matches at the beginning of a line so that "blah blah\nfoo" would match. '\A' matches at the beginning of the string so that "blah blah\nfoo" will not match, but "foo\nblah blah" will match. def anchor( rgxp ) Regexp.new "\\A#{rgxp.inspect[1...-1]}" end Blessings, TwP