2010-01-23 16 views
2

我想列舉所有的URL文本字符串,例如:如何識別和處理文本字符串中的所有URL?

text = "fasòls http://george.it sdafsda" 

對於找到的每個網址,我想調用一個函數該轉換的字符串。

現在,我使用的方法是這樣的:

msg = "" 
for i in text.split 
    if (i =~ URI::regexp).nil? 
     msg += " " + i 
     else 
     msg+= " " + method(i) 
    end 
end 
text = msg 

這工作,但它的長字符串緩慢。我如何加快速度?

+0

我清理了一下文本和語言,但如果這不是你要做的事,隨時恢復。 – 2010-01-23 14:24:02

回答

1

我覺得「GSUB」是你的朋友在這裏:

class UrlParser 
    attr_accessor :text, :url_counter, :urls 

    def initialize(text) 
    @text = parse(text) 
    end 

    private 
    def parse(text) 
     @counter = 0 
     @urls = [] 
     text.gsub(%r{(\A|\s+)(http://[^\s]+)}) do 
     @urls << $2 
     "#{$1}#{replace_url($2)}" 
     end 
    end 

    def replace_url(url) 
     @counter += 1 
     "[#{@counter}]" 
    end 
end 

parsed_url = UrlParser.new("one http://x.com/url two") 
puts parsed_url.text 
puts parsed_url.urls 

如果你真的需要長串的額外快速解析,你應該建立一個Ruby的C擴展與ragel

+0

如果沒有url文本返回零 – 2010-01-23 15:02:48

+0

Ouups,對不起,有一個錯字。它應該是「gsub」,而不是「gsub!」 (當然,你可能需要更強大的URL正則表達式)。 – gaspard 2010-01-23 15:09:37