Ruby链接为字符串中的URL
发布时间:2020-12-16 21:28:12 所属栏目:百科 来源:网络整理
导读:有一些关于使用正则表达式链接文本的帖子.最受欢迎的 is this post. 不过我的规格有点棘手: describe TextFormatter do def l(input) TextFormatter.gsub_links!(input){|link| "!!#{link}!!"} end it "should detect simple links" do l("http://www.cnn.c
有一些关于使用正则表达式链接文本的帖子.最受欢迎的
is this post.
不过我的规格有点棘手: 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 任何想法如何实现毛茸茸的正则表达式: 这是我到目前为止的地方(它未通过2次测试): def gsub_links!(input) regex = /https?://[-w+&@#/%?=~()|!:,.;]*[-w+&@#/%=~_()|]/ input.gsub!(regex) { |link| yield link } end 解决方法
我可能会错过一些背景,但为什么重新发明轮子?你在actionpack中尝试过auto_link吗?
$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" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |