【问题标题】:How do I modify \1 in gsub?如何在 gsub 中修改 \1?
【发布时间】:2013-06-03 08:20:15
【问题描述】:

当我看到一些与我的模式匹配的文本时,我想使用 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"

有没有办法可以在gsub 的右侧弄乱\1,这样我就可以获得以下信息?如果没有,最好的方法是什么?

【问题讨论】:

标签: ruby regex redcloth


【解决方案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)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 2011-06-29
    • 2010-09-05
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多