2013-06-27 78 views
4

我试图做一些基本的URL清洗,使简单URL清洁

www.google.com 
www.google.com/ 
http://google.com 
http://google.com/ 
https://google.com 
https://google.com/ 

http://www.google.com(或https://www.google.com的情况下https://是开头)所取代。

基本上我想检查一下是否有http/https开头,/最后在一个正则表达式中。

我是想这样的事情:在这种情况下

"https://google.com".match(/^(http:\/\/|https:\/\/)(.*)(\/)*$/)我得到: => #<MatchData "https://google.com" 1:"https://" 2:"google.com" 3:nil> 这是很好的。

不幸的是:

"https://google.com/".match(/^(http:\/\/|https:\/\/)(.*)(\/)*$/)我得到: => #<MatchData "https://google.com/" 1:"https://" 2:"google.com/" 3:nil>,并希望有2:"google.com" 3:"/"

任何想法如何做到这一点?

+1

顺便问一下,你是如何处理与多余的空白最后浏览的网址? – Jerry

+0

好问题,谢谢。将工作。 –

回答

6

如果您发现该错误很明显;)

你正在尝试:

^(http:\/\/|https:\/\/)(.*)(\/)*$ 

的答案是使用:

^(http:\/\/|https:\/\/)(.*?)(\/)*$ 

这使得运营商 “非贪婪” ,所以尾巴的正斜线不会被“。”吞噬。运营商。

编辑:

事实上,你应该使用:

^(http:\/\/|https:\/\/)?(www\.)?(.*?)(\/)*$ 

这样,你也将匹配您的第一两个例子,不具有“HTTP(S): //“ 在他们中。您还在分解“www”部分的价值/存在。在行动:http://www.rubular.com/r/VUoIUqCzzX

EDIT2:

我很无聊,想要完善这个:P

在这里你去:

^(https?:\/\/)?(?:www\.)?(.*?)\/?$ 

现在,所有你需要做的是更换您的网站与第一个匹配(或“http://”,如果为零),然后是“www。”,然后是第二个匹配。

在行动:http://www.rubular.com/r/YLeO5cXcck

(18月以后)编辑:

看看我真棒红宝石的宝石,这将有助于解决您的问题!

https://github.com/tom-lord/regexp-examples

/(https?:\/\/)?(?:www\.)?google\.com\/?/.examples # => 
    ["google.com", 
    "google.com/", 
    "www.google.com", 
    "www.google.com/", 
    "http://google.com", 
    "http://google.com/", 
    "http://www.google.com", 
    "http://www.google.com/", 
    "https://google.com", 
    "https://google.com/", 
    "https://www.google.com", 
    "https://www.google.com/"] 

/(https?:\/\/)?(?:www\.)?google\.com\/?/.examples.map(&:subgroups) # => 
    [[], 
    [], 
    [], 
    [], 
    ["http://"], 
    ["http://"], 
    ["http://"], 
    ["http://"], 
    ["https://"], 
    ["https://"], 
    ["https://"], 
    ["https://"]] 
+0

这正是我所期待的。谢谢。 –

+0

刚刚编辑我的答案,更好的版本:) –