Regular Expression to Create URL Permutations in Ruby


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # return 4 urls, with and without trailing slash, with and without www
  2. # useful for matching urls passed as params into some function,
  3. # "does this url exist?"... need to make sure you check permutations
  4. def url_permutations(url)
  5. url, params = url.split("?")
  6. # without_trailing_slash, with www
  7. a = url.gsub(/\/$/, "").gsub(/http(s)?:\/\/([^\/]+)/) do |match|
  8. protocol = "http#{$1.to_s}"
  9. domain = $2
  10. domain = "www.#{domain}" if domain.split(".").length < 3 # www.google.com == 3, google.com == 2
  11. "#{protocol}://#{domain}"
  12. end
  13. # with_trailing_slash, with www
  14. b = "#{a}/"
  15. # without_trailing_slash, without www
  16. c = a.gsub(/http(s)?:\/\/www\./, "http#{$1.to_s}://")
  17. # with_trailing_slash, without www
  18. d = "#{c}/"
  19.  
  20. [a, b, c, d].map { |url| "#{url}?#{params}"}
  21. end
  22.  
  23. puts url_permutations("http://google.com/search?q=http://google.com").inspect
  24. #=> [
  25. "http://www.google.com/search?q=http://google.com",
  26. "http://www.google.com/search/?q=http://google.com",
  27. "http://google.com/search?q=http://google.com",
  28. "http://google.com/search/?q=http://google.com"
  29. ]

URL: regular-expression-to-create-url-permutations-in-ruby

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.