我正在收到HTTParty和Hashie的最新推文.
tweet = Hashie::Mash.new HTTParty.get(http://twitter.com/statuses/user_timeline/ethnt.json).first
puts tweet.text
Run Code Online (Sandbox Code Playgroud)
我希望能够将每个link(http://*.*
)和usernames(@.
)转换为链接.两者的正则表达式是什么,以及如何实现它?
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)
Run Code Online (Sandbox Code Playgroud)
只要 URL 用空格填充或位于推文的开头和/或结尾,这种方法就有效。