2011-05-04 72 views
1

我有一個輸入字段,用戶可以發佈到Facebook頁面的鏈接。現在我正在使用正則表達式來驗證URL。如何替換部分輸入值?

URL_regex = /\A(http|https|ftp):\/\/([\w]*)\.([\w]*)\.(com|net|org|biz|info|mobi|us|cc|bz|tv|ws|name|co|me)(\.[a-z]{1,3})?/i 

我只想以下四個版本通過驗證:

  • https://www.facebook.com/redbull
  • http://www.facebook.com/redbull
  • www.facebook.com/redbull
  • facebook.com/redbull

ŧ母雞我想只想在數據庫中存儲「redbull」部分。我試過Rubular,但我無法弄清楚正則表達式的邏輯。

在此先感謝

找到了解決方案,THX到凱萊:

URL_regex = /\A((http|https):\/\/)?(www\.)?facebook\.com\/([\S]+)/i 

回答

1

這將只匹配4個變種你的建議,加上http://facebook.com/redbullhttps://facebook.com/redbull,因爲這些也可能是常見的變異。

/\A((http|https):\/\/)?(www\.)?facebook\.com\/(\w*)?/i 
+0

thx,很棒! – 2011-05-04 10:10:35

0

沒有正則表達式,你可以使用它:

var your_url = ''; //here, you place your URL 

console.log(your_url.slice(your_url.lastIndexOf('/') + 1)); 

這將給所需的輸出。

0

你快到了。你只需要添加另一個捕獲組。

\A(http|https|ftp):\/\/([\w]*)\.([\w]*)\.(com|net|org|biz|info|mobi|us|cc|bz|tv|ws|name|co|me)\/(\w+)? 

(http|https:ftp:\/\/)?\w*.\w+.(com|net|org|biz|info|mobi|us|cc|bz|tv|ws|name|co|me)\/(\w+) 

irb(main):014:0> if x =~ /\A(http|https|ftp):\/\/([\w]*)\.([\w]*)\.(com|net|org|biz|info|mobi|us|cc|bz|tv|ws|name|co|me)\/(\w+)?/ 
irb(main):015:1> puts $5 
irb(main):016:1> end 
redbull 
=> nil 
1

你已經得到的正則表達式不錯的答案,但我想指出的URI模塊:

>> require 'uri' 
#=> true 
>> uri = URI.parse "https://www.facebook.com/redbull" 
#=> #<URI::HTTPS:0x000001010a41a8 URL:https://www.facebook.com/redbull> 
>> uri.scheme 
#=> "https" 
>> uri.host 
#=> "www.facebook.com" 
>> uri.path 
#=> "/redbull" 

也許驗證的各個部分是很容易,一個大的正則表達式。