The array is created when i use the scan method so if i used reject it
would become a two pass process which is what i am doing anyway so I was
wondering if regular expressions had built in support for this.
The array is created when i use the scan method so if i used reject it
would become a two pass process which is what i am doing anyway so I was
wondering if regular expressions had built in support for this.
The array is created when i use the scan method so if i used reject it
would become a two pass process which is what i am doing anyway so I was
wondering if regular expressions had built in support for this.
As far as I know, this is not supported by Ruby’s 1.8.x regexps,
Negative lookahead is supported by that (and earlier) version.
The problem with negative lookahead is that - with the test data given
that the negative lookahead is difficult to get right:
irb(main):016:0> %w{foo.jpg foothumb.jpg}.each do |s|
irb(main):017:1* p [s, /\A\w+(?!thumb)\.jpg\z/ =~ s]
irb(main):018:1> end
[“foo.jpg”, 0]
[“foothumb.jpg”, 0]
=> [“foo.jpg”, “foothumb.jpg”]
I am not saying that it won’t work but off the top of my head I do not
have a solution that works. In any case, it’s easier to exclude
matches outside the regular expression engine. One way would be to
make thumb a capturing group and check whether the group is present,
like
irb(main):022:0> %w{foo.jpg foothumb.jpg}.each do |s|
irb(main):023:1* p [s, /\A\w+?(thumb)?\.jpg\z/ =~ s, $1]
irb(main):024:1> end
[“foo.jpg”, 0, nil]
[“foothumb.jpg”, 0, “thumb”]
=> [“foo.jpg”, “foothumb.jpg”]
and use that criterion for exclusion.
Now you can meditate on why the negative lookahead did not work.
If i use this expression…
/galleries.*(?=thumb).*jpg/
The results are just those lines containing the word thumb.
What I want to do is inverse this though and return only return that
DONT contain the word thumb.
Using Reg, my DSL for declarative programming in ruby, you can use the
logical operators (& | ~) to combine regexps. I call this ‘match
arithmetic’. The resulting objects implement === and =~, so they can
be used with Array#grep.
require ‘rubygems’
require ‘reg’
images=[“galleries/foo.jpg”, “galleries/foothumb.jpg”]
images.grep /galleries/.*.jpg$/ & ~/thumb.jpg$/ #in galleries and not thumb
There might well be a pure regexp way, but I’ve been unable to come up
with a clean one…
/^galleries.*([^t]humb|[^h]umb|[^u]mb|[^m]b|[^b]).jpg$/ #bleah
There. That’s a pretty nice pure regexp.
Now just make the group non capturing and you’re a tad more efficient.
Ah, brilliant! But it doesn’t quite work. It fails to match
“thumb_foo.jpg”, which probably should match here. A simple
modification should fix it, tho: