What's wrong with this regex for url validation in Ruby?

I am passing an array of urls to check. The function is below. It works when I only pass one url, but not more than one. the regex 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

      


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

thanks to everyone who took the time to help.

0


a source to share


5 answers


Try checking each url before matching it with 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 will help you find the url that doesn't match and you can work from there.

+2


a source


Perhaps you could just try to parse the uris and abort the 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 URIs. parsing

+1


a source


Check out Rubular . This is a great tool that has helped me on many occasions.

0


a source


ok, found the problem. I am trying to split a line like this

user_input.split ("\ r \ n")

it looks like it's wrong, so the function works correctly for one value and at most one value, because the array always contains one string, which is the input string: - (

0


a source


This method does what you ask. It can also be inside a class String

:

def linkify text
  text.gsub!(/\b((https?:\/\/|ftps?:\/\/|mailto:|www\.)([A-Za-z0-9\-_=%&@\?\.\/]+))\b/) {
    match = $1
    tail  = $3
    case match
    when /^www/     then  "<a href=\"http://#{match}\">Link</a>"
    when /^mailto/  then  "<a href=\"#{match}\">Link</a>"
    else                  "<a href=\"#{match}\">Link</a>"
    end
  }
  text
end

      

0


a source







All Articles