简体   繁体   中英

How do I modify \1 in gsub?

When I see some text that matches my pattern, I want to create a link to an external site using RedCloth that has a query link for it.

If I have something like:

Text 123 1234 12345

When I see that I want to replace it with:

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

If I let it keep the spaces, RedCloth won't notice this as a link correctly.

Here is where I am at:

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"

The probem is that RedCloth stops parsing after:

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

So I really need:

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

Is there a way I can mess with \\1 in the right hand side of gsub , such that I could get the following? If not, what's the best way to do this?

Ok, thanks to the comment by Narfanator I found the following: " $1 and \\1 in Ruby ".

The solutions was super easy:

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)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM