re = /^((http|https|ftp|ftps):\/\/)?(?<url_host>(\[[^\]]+\]|[^\/:\n]+))(?<url_port>(:\d+)?)(\/)?/m
str = 'sony.com
http://cnn.com/story
https://google.com:444/stuff
1.2.3.4:12/ok
1.2.3.4/ok
2.2.2.2:443
/dontmatchme
ftp://mononym/path
http://google.com
www.test
http://[2001:1890:1c00:6500::d:7]/rar/
[2001:1890:1c00:6500::d:7]
[2001:1890:1c00:6500::d:7]/test
http://[2001:1890:1c00:6500::d:7]:8080/rar/
[2001:1890:1c00:6500::d:7]:8080
[2001:1890:1c00:6500::d:7]:4/test
'
# Print the match result
str.scan(re) do |match|
puts match.to_s
end
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Ruby, please visit: http://ruby-doc.org/core-2.2.0/Regexp.html