简体   繁体   中英

Using gsub(), how to refer to the replaced string in the replacing string?

For example, I have a block of text which contains several instances of the string "{image=filename.jpg}" where filename.jpg can be any filename, and I want to replace everything within the {}'s with an image tag where the image is found by using the filename, eg Model.find_by_attachment_file_name("filename.jpg").

Is it possible to do this?

Edit:

Example input:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 

{image=some_file.png}

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Desired output:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 

<img src="/system/attachments/model/some_file.png">

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

The desired output's image tag's src attribute would be found by using Model.find_by_model_attachment_file_name("some_file.png").model_attachment.url

That is, something like:

string.gsub(/{image=.*}/, "<image src=#{ContentAttachment.find_by_content_image_file_name([???]).content_image.url(:main)}")

where [???] is replaced by a reference to what was replaced with gsub.

Or, how do I reference the first argument within the second argument of gsub?

Instead of setting second argument to gsub, appending a block to gsub does the job.

string.gsub(/\{image=(.*)\}/){
  # $1 will be "some_file.png"
  "<image src=#{ContentAttachment.find_by_content_image_file_name([$1]).content_image.url(:main)}"
}

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