我的目标是将Markdown转换为文本。我通过使用Redcarpet将markdown解析为HTML,然后使用#strip_tags来完成此操作。我的问题是链接,此方法仅保留链接的文本,而不保留链接本身。
例如:使用#strip_tags后,我需要保留href网址
# current
<a href="http://www.google.com">google</a> => google
# desired
<a href="http://www.google.com">google</a> => http://www.google.com google
我认为最好的方法是使用正则表达式,有人可以帮助实现吗?
我的目标是:
def contents_md
# instantiates Redcarpet
@markdown ||= begin
options = [autolink: true, fenced_code_blocks: true, no_intra_emphasis: true, hard_wrap: true, filter_html: true, gh_blockcode: true]
renderer = Redcarpet::Render::HTML.new(render_options = {})
Redcarpet::Markdown.new(renderer, *options)
end
# I need to run contents through a regex before passing to renderer that will turn something like this:
# [text1](https://www.stackoverflow.com) and [text2](https://www.google.com)
# into:
# text1 https://www.stackoverflow.com and text2 https://www.google.com
# then ill pass the result here, which will preserve my links that would be held in <a></a> instead of losing them
@markdown.render(contents)
end
# this will then be ran like:
<%= strip_tags(value.contents_md) %>
答案 0 :(得分:0)
您可以将gsub
与这样的正则表达式一起使用:
text = "[text1](https://www.stackoverflow.com) and [text2](https://www.google.com)"
text.gsub(/\[(.*?)\]\((.*?)\)/, "#{$1} #{$2}")
#=> "text2 https://www.google.com and text2 https://www.google.com"