本文介绍了Ruby Linkify字符串中的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
已有几篇关于使用正则表达式链接文本的文章. 此帖子.
There have been a few posts about linkifying text using a regex. The most popular is this post.
但是我的说明有些棘手:
However my spec is a little more tricky:
describe TextFormatter do
def l(input)
TextFormatter.gsub_links!(input){|link| "!!#{link}!!"}
end
it "should detect simple links" do
l("http://www.cnn.com").should == "!!http://www.cnn.com!!"
end
it "should detect multi links" do
l("http://www.cnn.com http://boats.com?help.asp").should == "!!http://www.cnn.com!! !!http://boats.com?help.asp!!"
end
it "should compensate for parans properly" do
l("(http://this.is?hello_world)").should == "(!!http://this.is?hello_world!!)"
end
it "should ignore existing links" do
s = "<A HREF='http://sam.com'> http://sam.com </A>"
l(s.dup).should == s
end
it "should allow parans" do
l("http://sam.com.au?(red)").should == "!!http://sam.com.au?(red)!!"
end
end
任何想法如何实现多用的Regex:
Any ideas how to implement the hairy Regex:
这是我到目前为止的位置(它未通过2次测试):
This is where I am so far (it fails 2 tests):
def gsub_links!(input)
regex = /https?\:\/\/[\-\w+&@#\/%?=~\(\)\|!:,.;]*[\-\w+&@#\/%=~_\(\)|]/
input.gsub!(regex) { |link|
yield link
}
end
推荐答案
我可能缺少某些上下文,但是为什么要重新发明轮子呢?您是否在actionpack
中尝试过auto_link
?
I might be missing some context, but why re-invent the wheel? Have you tried auto_link
in actionpack
?
$ gem install actionpack
$ irb -f --prompt simple
>> require 'action_view'
>> include ActionView::Helpers
>> auto_link("abc http://google.com xyz")
=> "abc <a href=\"http://google.com\">http://google.com</a> xyz"
>> auto_link("abc <a href='http://google.com'>google</a> xyz")
=> "abc <a href='http://google.com'>google</a> xyz"
这篇关于Ruby Linkify字符串中的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!