简体   繁体   English

使用gsub(),如何在替换字符串中引用替换的字符串?

[英]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"). 例如,我有一段文本,其中包含字符串“ {image = filename.jpg}”的多个实例,其中filename.jpg可以是任何文件名,并且我想用图像标记替换{}中的所有内容使用文件名找到图像的位置,例如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 通过使用Model.find_by_model_attachment_file_name("some_file.png").model_attachment.url可以找到所需输出的图像标签的src属性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. 其中[???]替换为对用gsub替换的内容的引用。

Or, how do I reference the first argument within the second argument of gsub? 或者,如何在gsub的第二个参数中引用第一个参数?

Instead of setting second argument to gsub, appending a block to gsub does the job. 除了将第二个参数设置为gsub之外,还可以在gsub后面附加一个块来完成这项工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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