timpone
timpone

Reputation: 19969

writing a short script to process markdown links and handling multiple scans

I'd like to process just links written in markdown. I've looked at redcarpet which I'd be ok with using but I really want to support just links and it doesn't look like you can use it that way. So I think I'm going to write a little method using regex but....

assuming I have something like this:

str="here is my thing [hope](http://www.github.com) and after [hxxx](http://www.some.com)"
tmp=str.scan(/\[.*\]\(.*\)/)

or if there is some way I could just gsub in place [hope](http://www.github.com) -> <a href='http://www.github.com'>hope</a>

How would I get an array of the matched phrases? I was thinking once I get an array, I could just do a replace on the original string. Are there better / easier ways of achieving the same result?

Upvotes: 0

Views: 80

Answers (2)

Zach Kemp
Zach Kemp

Reputation: 11904

I would actually stick with redcarpet. It includes a StripDown render class that will eliminate any markdown markup (essentially, rendering markdown as plain text). You can subclass it to reactivate the link method:

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 ...

This has the added benefits of being able to easily implement a few additional tags (say, if you decide you want paragraph tags to be inserted for line breaks).

Upvotes: 1

Qtax
Qtax

Reputation: 33918

You could just do a replace.

Match this:

\[([^[]\n]+)\]\(([^()[]\s"'<>]+)\)

Replace with:

<a href="\2">\1</a>

In Ruby it should be something like:

str.gsub(/\[([^[]\n]+)\]\(([^()[]\s"'<>]+)\)/, '<a href="\2">\1</a>')

Upvotes: 0

Related Questions