简体   繁体   中英

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. A simplified example appears below where I'm saving one of the captured groups -- \\3 -- for use in my replacement string.

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

Any advice is appreciated.

Use the block form of gsub and replace your \\3 references with $3 globals:

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.

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.

As an aside, is there a method you should be calling on what AnotherObject.find($3) returns?

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