2012-01-25 56 views
3

我基本上是編寫自己的Markdown解析器。我想檢測一個字符串中的URL,並用錨標記包裝它,如果它是一個有效的URL。例如:在文本中查找URL並將其包裹在錨定標記中

string = 'here is a link: http://google.com' 
# if string matches regex (which it does) 
# should return: 
'here is a link: <a href="http://google.com">http://google.com</a>' 

# but this would remain unchanged: 
string 'here is a link: google.com' 

我該如何做到這一點?

如果您可以將我指向現有的可用作示例的Ruby markdown解析器中的代碼,則可獲得額外獎勵。

+0

你想要什麼協議,允許? 'HTTP://'? '的https://'? 'FTP://'? 'IRC://'? '的telnet://'? – Phrogz

+1

以下是他們如何在Kramdown中執行此操作:

+0

注意:您必須刪除鏈接上面,使其工作。 –

回答

10

一般來說:使用正則表達式發現URL和包裹他們在您的HTML:

urls = %r{(?:https?|ftp|mailto)://\S+}i 
html = str.gsub urls, '<a href="\0">\0</a>' 

注意這個特殊的解決方案會變成這樣的文字:

See more at http://www.google.com. 

...到...

See more at <a href="http://www.google.com.">http://www.google.com.</a> 

所以,你可能想玩正則表達式來找出URL應該真正結束的地方。

+0

它真的很酷。謝謝 –

相關問題