gpt4 book ai didi

ruby - 如何引用ruby正则表达式

转载 作者:数据小太阳 更新时间:2023-10-29 07:23:54 25 4
gpt4 key购买 nike

我要转换字符串:

"{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>")

最佳答案

那个很酷的方法是 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>")

关于ruby - 如何引用ruby正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16399829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com