From: Andrew Johnson Date: 2005-01-27T16:10:59+09:00 Subject: Re: regex questions On Thu, 27 Jan 2005 12:21:35 +0900, Jeff Davis wrote: > In python the regexes allow you to call a function instead of just > substitute the values (see for > more details). That seems quite useful, is there something similar in ruby? Yes, #sub and #gsub can be passed a block to be evaluated for the replacement value. > Also, let's say I want match anything between "a" and "b" unless it > contains the word "foo". I could write two regexes like so: > > if str =~ /a(.*)b/ and str !~ /a(.*foo.*)b/ Careful, consider this string: str = 'afoolbalmnbaopbafoob' which has two sets of a..b that don't contain 'foo', but your pairing rejects it because a..foo..b can also be found. > Is there a good way to make that kind of logic into one regex? Is there > some kind of "intersect" operator or a "not" operator? A fairly standard way is to use negative look-ahead and inch ahead one character at a time like: re = %r{a((?:(?!foo).)*?)b} str = 'afoolbalmnbaopbafoob' str.scan(re).each do |m| p m end __END__ ["lmn"] ["op"] regards, andrew -- Andrew L. Johnson http://www.siaris.net/ But puzzles in programming are what make it challenging and fun sometimes... you always end up learning one more way not to do something each time. -- Brad Fenwick