6

正規表現を使用してテキストをリンクすることについての投稿がいくつかあります。最も人気のあるのはこの投稿です。

ただし、私の仕様はもう少し注意が必要です。

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
4

1 に答える 1

13

私はいくつかの文脈を見逃しているかもしれませんが、なぜ車輪を再発明するのですか?試してみauto_linkました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"
于 2009-09-18T02:58:03.277 に答える