[英]Can't get regex captured group working in Ruby on Rails method
I need to parse and replace text using gsub and a regular expression. 我需要使用gsub和正则表达式来解析和替换文本。 A simplified example appears below where I'm saving one of the captured groups -- \\3 -- for use in my replacement string.
下面是一个简化的示例,其中我保存了一个捕获的组-\\ 3-用于替换字符串。
my_map.gsub(/(\shref=)(\")(\d+), ' href="/created_path/' + '\3' + '" ' + ' title="' + AnotherObject.find('\3')'"')
In the first use of the captured value, I'm simply displaying it to build the new path. 在第一次使用捕获的值时,我只是显示它以构建新路径。 In the second example, I am calling a find with the captured value.
在第二个示例中,我将调用具有捕获值的查找。 The second example will not work.
第二个示例不起作用。
I've tried various ways of escaping the value ("\\3", ''\\3'', etc) and even built a method to test displaying the value (works) or using the value in a method (doesn't work). 我尝试了各种转义值的方式(“ \\ 3”,“ \\ 3”等),甚至构建了一种方法来测试显示值(有效)或在方法中使用值(无效) )。
Any advice is appreciated. 任何建议表示赞赏。
Use the block form of gsub
and replace your \\3
references with $3
globals: 使用
gsub
的块形式并将\\3
引用替换$3
全局变量:
my_map.gsub(/(\shref=)(\")(\d+)/) { %Q{ href="/created_path/#{$3}" title="#{AnotherObject.find($3)"} }
I also switched to %Q{}
for quoting to avoid the confusing quote mixing and concatenation. 我还切换到
%Q{}
进行引用,以避免混淆的引用混合和串联。
The second argument in the replacement-string form of gsub
(ie the version of gsub
that you're trying to use) will be evaluated and concatenated before gsub
is called and **before **the \\3
value is available so it won't work. gsub
替换字符串形式的第二个参数(即您要使用的gsub
的版本)将在调用gsub
之前和**之前** \\3
值可用之前进行求值和连接,它将不会工作。
As an aside, is there a method you should be calling on what AnotherObject.find($3)
returns? AnotherObject.find($3)
说一句,是否应该调用AnotherObject.find($3)
返回的方法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.