How to search through array with Regex?

后端 未结 3 1604
萌比男神i
萌比男神i 2021-01-26 09:09

So I am trying to match email to email domains (ie bob@test to @test.com). Both the array of emails and email domains are in separate arrays. Right now I am trying the following

相关标签:
3条回答
  • 2021-01-26 09:40
    @domains = ["hotmail.com", "gmail.com"]
    @emails = ["blah@hotmail.com", "you@yahoo.com", "me@gmail.com"]
    @a = []
    
    @domains.each {|d|
      @a << @emails.select{ |e| e=~ /#{d}/ }
    }
    
    @a.flatten! #=> ["blah@hotmail.com", "me@gmail.com"]
    

    Now I can do stuff with @a

    0 讨论(0)
  • 2021-01-26 09:45

    You can use each_with_object with a hash, grep the @emails array for matching patterns and associate both:

    @domains.each_with_object Hash.new do |domain, matches|
      matches[domain] = @emails.grep domain
    end
    
    0 讨论(0)
  • 2021-01-26 09:46

    It is not clear what you are trying to do with a regex. This is a minimum fix to make it run. It does not use a regex.

    @Domains.each do |domain|
      if @Emails.any?{|email| email.end_with?(domain)} 
        #do stuff
      end
    end
    
    0 讨论(0)
提交回复
热议问题