Ruby linkuje adresy URL w łańcuchach
Odnotowano kilka postów na temat linkfying tekstu za pomocą wyrażenia regularnego. Najbardziej popularneto ten post.
Jednak moja specyfikacja jest nieco trudniejsza:
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
Jakieś pomysły, jak wdrożyć włochaty Regex:
To jest miejsce, gdzie do tej pory jestem (zawodzi 2 testy):
def gsub_links!(input)
regex = /https?\:\/\/[\-\w+&@#\/%?=~\(\)\|!:,.;]*[\-\w+&@#\/%=~_\(\)|]/
input.gsub!(regex) { |link|
yield link
}
end