【发布时间】:2018-02-16 07:48:29
【问题描述】:
这里有一段典型的gsub 代码:
str = '[caption id="attachment_3655" align="aligncenter" width="1024"]<a href="http://test.com/wp-content/uploads/2018/01/sample-image.jpg"><img class="size-large wp-image-3655" src="{{ site.baseurl }}/assets/sample-image-1024x768.jpg" alt="" width="1024" height="768" /></a> Image title[/caption]'
p str.gsub(/\[caption.*?\]<a href=\"(.+?)\".*?><img .*?\/><\/a>(.+?)\[\/caption\]/) { |match|
href = $1.sub("http://test.com/wp-content/uploads/", "")
title = $2
"#{href} - #{title}"
}
在此调用之后$1.sub("http://test.com/wp-content/uploads/", "") 捕获数据$2 变为nil。如果我首先访问上面的$2,它就可以工作。为什么调用 sub() 会使捕获无效?
【问题讨论】: