有一些关于使用正则表达式链接文本的帖子。最受欢迎是这个帖子吗 https://stackoverflow.com/questions/758135/c-code-to-linkify-urls-in-a-string.
然而我的规范有点棘手:
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
关于如何实现毛茸茸的正则表达式的任何想法:
这就是我到目前为止的情况(两次测试失败):
def gsub_links!(input)
regex = /https?\:\/\/[\-\w+&@#\/%?=~\(\)\|!:,.;]*[\-\w+&@#\/%=~_\(\)|]/
input.gsub!(regex) { |link|
yield link
}
end
我可能会遗漏一些上下文,但为什么要重新发明轮子呢?你有没有尝试过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"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)