0
用Ruby的正則表達式與HTML我怎麼能代替降價格式:用正則表達式替換單詞的句子在紅寶石
hallo _html_ dan *gaga* sas *tes*
是
hallo <em>html</em> dan <strong>gaga</strong> sas <strong>tes</strong>
用Ruby的正則表達式與HTML我怎麼能代替降價格式:用正則表達式替換單詞的句子在紅寶石
hallo _html_ dan *gaga* sas *tes*
是
hallo <em>html</em> dan <strong>gaga</strong> sas <strong>tes</strong>
有該媒體鏈接的寶石,如redcarpet
這裏是一個使用默認降價渲染器的示例,但如果您需要不同的語法,則可以使用自己的渲染器。
require 'redcarpet'
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)
markdown.render("**This** _is_ an [example](http://example.org/).")
# => "<p><strong>This</strong> <em>is</em> an <a href="http://example.org/">example</a>.</p>"
總的來說這是一個壞主意,使用正則表達式與HTML或推倒重來,但如果你堅持,在這裏一個簡單的例子,你怎麼能做到這一點。
# create a hash with our regular expressions and replacements
map = { /_(.+?)_/ => '<em>\1</em>', /\*(.+?)\*/ => '<strong>\1</strong>'}
markdown = "hallo _html_ dan *gaga* das *test*"
# enumerate the hash and replace the expressions with their replacement
# tap returns the result to itself
markdown.tap{|md| map.each { |re, v| md.gsub!(re, v)}}
# => hallo <em>html</em> dan <strong>gaga</strong> das <strong>test</strong>
@Cary Swoveland嗨卡里,我是那種你,你一個風扇知道。謝謝你的建議,但你爲什麼不回答這個問題?我感覺就像瞄準一個移動的目標,所以我刪除了它。在臨睡前看到這一點,我會打電話給休息日。 – peter
的可能的複製[紅寶石正則表達式替換(https://stackoverflow.com/questions/46555955/ruby-regex-replace) – colincr