Search code examples
rubyregexreplace

Ruby replace string with captured regex pattern


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 }

Solution

  • 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"