tags:

views:

406

answers:

5

I am passing an array of URLs to validate. The function is below. It works when I pass just one URL, but not more than one. the regular expression seems to be correct. Where am I going wrong?

  def check_urls (list) 
    regexp =/(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix 
    list.each do |url| 
     if not regexp.match(url) 
      return false 
     end 
    end 
    return true 
  end
+2  A: 

Try inspecting each url before you match it against the regex:

def check_urls (list) 
  regexp =/(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix        
  list.all? do |url|
    p url # see what URL is getting inspected
    regexp =~ url  # make sure it matches the regexp
  end
end

This should help you find the URL that doesn't match it, and you can work from there.

rampion
A: 

Maybe you could just try to parse the uris and abort on error.

def check_urls(list = [])
  list.to_a.all? do |uri_string|
    uri = URI.parse(uri_string) rescue nil
    uri && uri.scheme == "http"
  end
end

See also the docs for Enumerable#all and URI.parse

levinalex
A: 

Check out Rubular. It's a great little tool that has helped me out in numerous cases.

Nick Stamas
A: 

ok, found the prob. I am trying to split the string like this

user_input.split("\r\n")

looks like this is wrong, that is why the function is working correctly for one value and not more than one value, because the array always contains one string, which is the input string :-(

+1  A: 

fixed the error. nothing wrong the regex function, just the splitting was done wrong.

thanks to all who took time to help.