Re: Doing an AND in regexp char class
by Joel VanderWerf other posts by this author
May 8 2008 5:00PM messages near this date
Re: Doing an AND in regexp char class
|
Re: Doing an AND in regexp char class
Todd Benson wrote:
> On Thu, May 8, 2008 at 6:07 PM, ara.t.howard <ara.t.howard@[...].com> wrote:
> > On May 8, 2008, at 3:40 PM, Todd Benson wrote:
> >> This question arises out of a couple of recent threads and may or may
> >> not be a Ruby-specific question.
> >>
> >> I can check with a character class if one of the characters in the
> >> class exists or does not exist, but can I use a regexp to check if a
> >> string absolutely contains all of the characters in the class?
> >>
> >> Using a set perspective, I can do it like this in irb...
> >>
> >> s1 = "hello there"
> >> s2 = "ohi"
> >> (s2.unpack('c*') & s1.unpack('c*')).size == s2.size
> >>
> >> => false
> >>
> >> I use unpack to avoid creating a bunch of String objects, one for each
> >> element in the array, which would happen if I used #split. What I'm
> >> wondering is if there is a way to do this with a simple regexp.
> >>
> >> Thanks,
> >> Todd
> > cfp:~ > cat a.rb
> > class String
> > def all_chars? chars
> > tr(chars, '').empty?
> > end
> > end
> >
> > p 'foobar'.all_chars?('rabof')
> > p 'foobar'.all_chars?('abc')
> > p 'foobar'.all_chars?('')
> >
> >
> >
> > cfp:~ > ruby a.rb
> > true
> > false
> > false
>
> Cool :) #tr is one of those useful methods I somehow consistently forget about.
But it can be done with regex, right? It's just more elegant with tr.
class String
def all_chars? chars
if chars.empty?
empty?
else
/\A[#{chars}]*\z/ === self
end
end
end
p 'foobar'.all_chars?('rabof') # => true
p 'foobar'.all_chars?('abc') # => false
p 'foobar'.all_chars?('') # => false
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407
Thread:
Todd Benson
Rick DeNatale
Ara.T.Howard
Pit Capitain
Todd Benson
Joel VanderWerf
7stud --
David A. Black
7stud --
Todd Benson
David A. Black
Joel VanderWerf
Todd Benson
David A. Black
Joel VanderWerf
David A. Black
Ara.T.Howard
Robert Dober
|