2012-06-01 10 views
1

我是新創建正則表達式的,所以這可能只是一個愚蠢的疏忽,但我的正則表達式(旨在匹配URL的)不起作用。我的目標是有它匹配像任何網址:我的正則表達式與數字不匹配

http://www.somewhere.com 
somewhere.com 
https://ww3.some_where-hi.com 
www.goop.go/herp/derp.lol 

我建在下面,但是,它不匹配一個URL像http://t.co/GZhtBh6c正則表達式,它停在6號匹配(如www.regexpal.com確定)。

((http|https)://)?([a-z0-9]+\.)?[a-z0-9\-_]+.[a-z]+(/[a-z0-9\-_]*)*([a-z0-9\-_]*\.[a-z]+){0,1} 

有誰能告訴我爲什麼這不起作用嗎?另外,我相信這不是最好的解決方案。如果你有一個更優雅的正則表達式,我很樂意看到它。

P.S.這個正則表達式將與JavaScript一起使用。

+0

請注意,您的正則表達式也將錯過的不同部分'HTTP:// WWW.GOOGLE.COM',例如。 – sarnold

+2

哦,我會使用大小寫不敏感的模式,但是謝謝 – diracdeltafunk

+0

一般情況下,不要使用正則表達式來匹配網址 - 有很多更好的方法。如果這是一個使用正則表達式的教學練習,那麼這很好,但不要在任何「生產」代碼中進行。 –

回答

4

驗證字符串是否包含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 
} 
+2

希望我可以給另一個+1的評論... – sarnold

+0

這工作,謝謝。 – diracdeltafunk

-1

使用[A-z]而不是[a-z] 您的小a-z只匹配小寫字母。

+0

我會不區分大小寫模式。 – diracdeltafunk

+0

這並不回答與數字有關的問題,但無論如何,'[A-z]'是[A-Za-z]的有效快捷方式?有趣的.. –

+1

你嘗試過'http:// t.co/GZhtBh6c'的情況嗎? – sarnold