用ruby中的正则表达式替换句子中的单词

用ruby中的正则表达式替换句子中的单词,ruby,regex,Ruby,Regex,如何使用Ruby regex用HTML替换标记格式: hallo _html_ dan *gaga* sas *tes* 将来 hallo-html-dangagasastes 这方面有很多现成的宝石,例如 这里是一个示例,我使用默认的markdown渲染器,但是如果需要不同的语法,您可以制作自己的渲染器 require 'redcarpet' markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML) markdown.render

如何使用Ruby regex用HTML替换标记格式:

hallo _html_ dan *gaga* sas *tes*
将来

hallo-html-dangagasastes

这方面有很多现成的宝石,例如

这里是一个示例,我使用默认的markdown渲染器,但是如果需要不同的语法,您可以制作自己的渲染器

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>"
需要“红地毯”
markdown=red地毯::markdown.new(red地毯::呈现::HTML)
markdown.render(“**这**是一个[示例](http://example.org/).")
#=>“这是一个
一般来说,将正则表达式与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>
#使用正则表达式和替换项创建哈希
map={/\(.+?)\/=>'\1',/\*(.+?)\*/=>'\1'}
markdown=“你好”\html\u dan*gaga*das*test*
#枚举散列并用表达式的替换项替换表达式
#点击将结果返回给自己
markdown.tap{md|map.each{re,v{md.gsub!(re,v)}
#=>你好html dangagadastest

可能是@Cary Swoveland的复制品你好,Cary,你知道我是你的粉丝。谢谢你的建议,但是你为什么不回答这个问题呢?我想瞄准一个移动的目标,所以我把它删掉了。我在睡觉前看到了这个,我今天就要休息了。
# 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>