Notice:
As pointed by @CGuess, there's a bug with this issue and it's been documented for over 9 years now that validation is not the purpose of this regular expression (see https://bugs.ruby-lang.org/issues/6520).
Use the URI
module distributed with Ruby:
require 'uri'
if url =~ URI::regexp
# Correct URL
end
Like Alexander Günther said in the comments, it checks if a string contains a URL.
To check if the string is a URL, use:
url =~ /A#{URI::regexp}z/
If you only want to check for web URLs (http
or https
), use this:
url =~ /A#{URI::regexp(['http', 'https'])}z/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…