2011-05-04 74 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" 

也许验证的各个部分是很容易,一个大的正则表达式。