我想处理用markdown编写的链接。我看过redcapet,我可以使用它,但我真的想支持链接,看起来你不能这样使用它。所以我想我会用regex编写一个小方法,但是......
假设我有这样的事情:
str="here is my thing [hope](http://www.github.com) and after [hxxx](http://www.some.com)"
tmp=str.scan(/\[.*\]\(.*\)/)
或者如果有某种方法我可以只使用gsub [hope](http://www.github.com) -> <a href='http://www.github.com'>hope</a>
我如何获得匹配短语的数组?我想,一旦我得到一个数组,我就可以对原始字符串进行替换。是否有更好/更简单的方法来实现相同的结果?
答案 0 :(得分:1)
我实际上会坚持使用redcarpet。它包含一个StripDown
render class,它将消除任何降价标记(实际上,将降价标记为纯文本)。您可以将其子类化以重新激活链接方法:
require 'redcarpet'
require 'redcarpet/render_strip'
module Redcarpet
module Render
class LinksOnly < StripDown
def link(link, title, content)
%{<a href="#{link}" title="#{title}">#{content}</a>}
end
end
end
end
str="here is my thing [hope](http://www.github.com) and after [hxxx](http://www.some.com)"
md = Redcarpet::Markdown.new(Redcarpet::Render::LinksOnly)
puts md.render(str)
# => here is my thing <a href="http://www.github.com" title="">hope</a> and ...
这具有额外的好处,即能够轻松实现一些额外的标签(例如,如果您决定插入段落标签以进行换行)。
答案 1 :(得分:0)
你可以做一个替换。
匹配这个:
\[([^[]\n]+)\]\(([^()[]\s"'<>]+)\)
替换为:
<a href="\2">\1</a>
在Ruby中应该是这样的:
str.gsub(/\[([^[]\n]+)\]\(([^()[]\s"'<>]+)\)/, '<a href="\2">\1</a>')