如何在gsub中修改\ 1?

时间:2013-06-02 21:14:49

标签: ruby regex redcloth

当我看到一些与我的模式匹配的文本时,我想使用具有查询链接的RedCloth创建指向外部网站的链接。

如果我有类似的话:

Text 123 1234 12345

当我看到我想用以下内容替换它时:

"Text 123 1234 12345":http://site.com/query?value=Text%20123%201234%2012345

如果我让它保留空格,RedCloth将不会正确地注意到这一点。

我在这里:

s = "this is a string which has Text 123 1234 12345 "

s = s.s.gsub(/(Text \d+ \d+ \d+)/,'"\1":http://site.com/query?value=\1'

=> "Text 123 1234 12345":http://site.com/query?value=Text 123 1234 12345"

探测器是RedCloth在:

之后停止解析
 "Text 123 1234 12345":http://site.com/query?value=Text 

所以我真的需要:

"Text 123 1234 12345":http://site.com/query?value=Text%20123%201234%2012345"

我是否有办法在\1的右侧混淆gsub,以便我可以获得以下内容?如果没有,最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

好的,感谢Narfanator的评论,我发现了以下内容:“$1 and \1 in Ruby”。

解决方案非常简单:

s = "this is a string which has Text 123 1234 12345 "
s = s.s.gsub(/(Text \d+ \d+ \d+)/){|x| "\"" + x + "\":https://site.com/query?value=" + CGI::escape(x)}
相关问题