驗證字符串是否包含RFC 3986中指定的URL。支持絕對和相對URL。
這符合您提供的樣品和更多。它也可以讓你提取網址
^
(# Scheme
[a-z][a-z0-9+\-.]*:
(# Authority & path
//
([a-z0-9\-._~%!$&'()*+,;=][email protected])? # User
([a-z0-9\-._~%]+ # Named host
|\[[a-f0-9:.]+\] # IPv6 host
|\[v[a-f0-9][a-z0-9\-._~%!$&'()*+,;=:]+\]) # IPvFuture host
(:[0-9]+)? # Port
(/[a-z0-9\-._~%!$&'()*+,;=:@]+)*/? # Path
|# Path without authority
(/?[a-z0-9\-._~%!$&'()*+,;=:@]+(/[a-z0-9\-._~%!$&'()*+,;=:@]+)*/?)?
)
|# Relative URL (no scheme or authority)
([a-z0-9\-._~%!$&'()*+,;[email protected]]+(/[a-z0-9\-._~%!$&'()*+,;=:@]+)*/? # Relative path
|(/[a-z0-9\-._~%!$&'()*+,;=:@]+)+/?) # Absolute path
)
# Query
(\?[a-z0-9\-._~%!$&'()*+,;=:@/?]*)?
# Fragment
(\#[a-z0-9\-._~%!$&'()*+,;=:@/?]*)?
$
在javascript中這成爲
if (/^([a-z][a-z0-9+\-.]*:(\/\/([a-z0-9\-._~%!$&'()*+,;=][email protected])?([a-z0-9\-._~%]+|\[[a-f0-9:.]+\]|\[v[a-f0-9][a-z0-9\-._~%!$&'()*+,;=:]+\])(:[0-9]+)?(\/[a-z0-9\-._~%!$&'()*+,;=:@]+)*\/?|(\/?[a-z0-9\-._~%!$&'()*+,;=:@]+(\/[a-z0-9\-._~%!$&'()*+,;=:@]+)*\/?)?)|([a-z0-9\-._~%!$&'()*+,;[email protected]]+(\/[a-z0-9\-._~%!$&'()*+,;=:@]+)*\/?|(\/[a-z0-9\-._~%!$&'()*+,;=:@]+)+\/?))(\?[a-z0-9\-._~%!$&'()*+,;=:@\/?]*)?(#[a-z0-9\-._~%!$&'()*+,;=:@\/?]*)?$/im.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
請注意,您的正則表達式也將錯過的不同部分'HTTP:// WWW.GOOGLE.COM',例如。 – sarnold
哦,我會使用大小寫不敏感的模式,但是謝謝 – diracdeltafunk
一般情況下,不要使用正則表達式來匹配網址 - 有很多更好的方法。如果這是一個使用正則表達式的教學練習,那麼這很好,但不要在任何「生產」代碼中進行。 –