将 URL 和 @* 转换为链接 [英] Turn URLs and @* into links

查看:78
本文介绍了将 URL 和 @* 转换为链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过 HTTParty 和 Hashie 获取我的最新推文.

I'm getting my latest tweets with HTTParty and Hashie like so.

tweet = Hashie::Mash.new HTTParty.get(http://twitter.com/statuses/user_timeline/ethnt.json).first
puts tweet.text

我希望能够将每个链接 (http://*.*) 和用户名 (@.) 转换为链接.这两个的正则表达式是什么,我将如何实现它?

I want to be able to turn every link (http://*.*) and usernames (@.) into links. What would the regex for both of these be, and how would I implement it?

推荐答案

def link_urls_and_users s

    #regexps
    url = /( |^)http:\/\/([^\s]*\.[^\s]*)( |$)/
    user = /@(\w+)/

    #replace @usernames with links to that user
    while s =~ user
        s.sub! "@#{$1}", "<a href='http://twitter.com/#{$1}' >#{$1}</a>"
    end

    #replace urls with links
    while s =~ url
        name = $2
        s.sub! /( |^)http:\/\/#{name}( |$)/, " <a href='http://#{name}' >#{name}</a> "
    end

     s

end


puts link_urls_and_users(tweet.text)

只要网址以空格填充或位于推文的开头和/或结尾,此方法就有效.

This works, so long as URLs are padded by spaces or are at the beginning and/or end of the tweet.

这篇关于将 URL 和 @* 转换为链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆