Ruby replace string with captured regex pattern

JD Isaacks picture JD Isaacks · Mar 28, 2012 · Viewed 110.4k times · Source

I am having trouble translating this into Ruby.

Here is a piece of JavaScript that does exactly what I want to do:

function get_code(str){
    return str.replace(/^(Z_.*): .*/,"$1")​​​​​​​​​​​​​​​​​​​​​​​​​​​;
}

I have tried gsub, sub, and replace but none seem to do what I am expecting.

Here are examples of things I have tried:

"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/) { |capture| capture }
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "$1")
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "#{$1}")
"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\1")
"Z_sdsd: sdsd".gsub(/(.).*/) { |capture| capture }

Answer

Michael Kohl picture Michael Kohl · Mar 28, 2012

Try '\1' for the replacement (single quotes are important, otherwise you need to escape the \):

"foo".gsub(/(o+)/, '\1\1\1')
#=> "foooooo"

But since you only seem to be interested in the capture group, note that you can index a string with a regex:

"foo"[/oo/]
#=> "oo"
"Z_123: foobar"[/^Z_.*(?=:)/]
#=> "Z_123"