假设用户在博客上提交以下评论:
@SO -伟大的社区,但我们也看到了一些伟大的社区在堆栈溢出。同时,谷歌的Gmail (http://gmail.com)是一个有着无限界限的社区的一个很好的例子。我只是想知道是否有人真的会和http://www.twitter.com这样的东西针锋相对。你认为如何?
备注:第三个url实际上是作为纯文本发布的,但因此将其转换为一个超链接。
无论如何,总url和超级链接数应该是3。
所以,从Rubyand/或Rails的角度来看:如何计算Ruby字符串中出现的urls和超链接的数量?
发布于 2010-07-18 00:17:00
这很容易,尽管相对来说很天真:
string.count("http://")当然,如果没有领先的"http://"“,它不会找到链接,但这可能是一个合理的假设。
发布于 2010-07-17 21:20:39
最简单的方法是扫描"http“模式,但实际上它可能更复杂,因为有时候urls在乞讨时没有得到"http://”“。
string = "@SO - Great community, but we've also seen some great communities at <a href='http://blabla'>Stack Overflow</a>. At the same time Google's Gmail (http://gmail.com) is a great example of a community with endless bounds. I'm just wondering if anyone will really go toe-to-toe with something like http://www.twitter.com. What do you think?"
string.scan(/http/).size #=> 3发布于 2010-07-17 21:23:53
使用正则表达式是一种好方法。下面是一个如何做到这一点的例子:
yourpost.each do |yourword|
if yourword =~ /^(((ht|f)tps?\:\/\/)|~/|/)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5})(:[\d]{1,5})?)/?(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?/
puts %Q!We found #{$&} an URL in #{$1}!
end
end有关正则表达式匹配URL的进一步讨论,请参见这帖子。
https://stackoverflow.com/questions/3273297
复制相似问题