如何引用ruby正则表达式

时间:2013-05-06 13:29:04

标签: ruby regex

我想转换字符串:

"{john:123456}" 

为:

"<script src='https://gist.github.com/john/123456.js'>"

我写了一个有效的方法,但它非常愚蠢。就像这样:

def convert
    args = []

    self.scan(/{([a-zA-Z0-9\-_]+):(\d+)}/) {|x| args << x}  

    args.each do |pair|
       name = pair[0]
       id = pair[1]
       self.gsub!("{" + name + ":" + id + "}", "<script src='https://gist.github.com/#{name}/#{id}.js'></script>")
    end 

    self
end

有没有办法像下面的cool_method那样做?

"{john:123}".cool_method(/{([a-zA-Z0-9\-_]+):(\d+)}/, "<script src='https://gist.github.com/$1/$2.js'></script>")

4 个答案:

答案 0 :(得分:7)

那个很酷的方法是gsub。你真是太近了!只需将$ 1和$ 2更改为\\ 1和\\ 2

http://ruby-doc.org/core-2.0/String.html#method-i-gsub

"{john:123}".gsub(/{([a-zA-Z0-9\-_]+):(\d+)}/, 
  "<script src='https://gist.github.com/\\1/\\2.js'></script>")

答案 1 :(得分:1)

我愿意

def convert
    /{(?<name>[a-zA-Z0-9\-_]+):(?<id>\d+)}/ =~ self
    "<script src='https://gist.github.com/#{name}/#{id}.js'></script>"
end

有关详细信息,请参阅http://ruby-doc.org/core-2.0/Regexp.html#label-Capturing

答案 2 :(得分:1)

s = "{john:123456}".scan(/\w+|\d+/).each_with_object("<script src='https://gist.github.com") do |i,ob|
  ob<< "/" + i
end.concat(".js'>")
p s #=> "<script src='https://gist.github.com/john/123456.js'>"

答案 3 :(得分:1)

这看起来像一个JSON字符串,因此,正如@DaveNewton所说,将其视为一个:

require 'json'
json = '{"john":123456}' 
name, value = JSON[json].flatten
"<script src='https://gist.github.com/#{ name }/#{ value }.js'></script>"
=> "<script src='https://gist.github.com/john/123456.js'></script>"

为什么不将它视为字符串并在其上使用正则表达式?因为JSON不是通过正则表达式解析的简单格式,当值发生变化或数据字符串变得更复杂时,这可能导致错误。